首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在一个`ForEach`中只选择一个按钮?

在一个ForEach中只选择一个按钮可以通过以下方式实现:

  1. 使用@State属性来跟踪选中的按钮。在循环中为每个按钮创建一个@State属性,用于表示按钮是否被选中。
代码语言:txt
复制
struct ContentView: View {
    struct Item: Identifiable {
        let id = UUID()
        let title: String
    }
    
    @State private var selectedButton: Item?
    
    let items = [
        Item(title: "Button 1"),
        Item(title: "Button 2"),
        Item(title: "Button 3")
    ]
    
    var body: some View {
        VStack {
            ForEach(items) { item in
                Button(action: {
                    selectedButton = item
                }) {
                    Text(item.title)
                        .foregroundColor(selectedButton == item ? .red : .blue)
                }
            }
        }
    }
}

在上述代码中,我们使用@State属性selectedButton来表示选中的按钮。当按钮被点击时,我们更新selectedButton的值为当前按钮的Item对象。在循环中,我们根据selectedButton的值来设置按钮的颜色,以区分选中和未选中状态。

  1. 使用Toggle来实现单选按钮的效果。在循环中使用Toggle来表示按钮的选中状态。
代码语言:txt
复制
struct ContentView: View {
    struct Item: Identifiable {
        let id = UUID()
        let title: String
        var isSelected = false
    }
    
    @State private var items = [
        Item(title: "Button 1"),
        Item(title: "Button 2"),
        Item(title: "Button 3")
    ]
    
    var body: some View {
        VStack {
            ForEach(items) { item in
                Toggle(isOn: $items[getIndex(for: item)].isSelected) {
                    Text(item.title)
                        .foregroundColor(item.isSelected ? .red : .blue)
                }
            }
        }
    }
    
    private func getIndex(for item: Item) -> Int {
        guard let index = items.firstIndex(where: { $0.id == item.id }) else {
            fatalError("Item not found")
        }
        return index
    }
}

在上述代码中,我们为每个按钮的Item对象添加了一个isSelected属性来表示按钮是否被选中。在循环中,我们使用Toggle来表示按钮的选中状态,并通过$items[getIndex(for: item)].isSelected将选中状态绑定到Item对象的isSelected属性上。根据isSelected的值,我们设置按钮的颜色以区分选中和未选中状态。

这两种方法都可以实现在一个ForEach中只选择一个按钮的效果,具体选择哪种方法取决于你的需求和UI设计。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

共1个视频
多媒体应用设计师
福大大架构师每日一题
多媒体应用设计师考试是软考中级水平的一门考试,一年只有一次,在下半年。考试时间通常在11月的第一个周末,此次考试为纸笔考试改为机考。考试内容包括选择题和案例综合题,其中案例综合题较难但会给出提示。考试教材为官方教材第2版,而考纲内容必须全部掌握。考试大纲的重点章节需要仔细阅读,历年考试题目以2018年及以后为准。
领券