首页
学习
活动
专区
工具
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设计。

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

相关·内容

  • 领券