gpt4 book ai didi

swiftui - 我怎样才能在 SwiftUI 中实现类似于 radiogroup 的一种可能选择

转载 作者:行者123 更新时间:2023-12-05 09:10:06 28 4
gpt4 key购买 nike

如何在 SwiftUI 中使用 View 列表实现类似于一组单选按钮的单一选择?

sample ss

最佳答案

按下按钮时,您可以存储选择的值。

并且您可以根据选择的按钮设置按钮样式。

下面的代码应该可以满足您的需求。最后按下的按钮将被选中,并且只有被选中的按钮是蓝色的,因为样式是基于属性的。另一个按钮清除选择。

struct ContentView: View {

let buttons = ["A", "B", "C"]
@State public var buttonSelected: Int?

var body: some View {
VStack(spacing: 20) {
ForEach(0..<buttons.count) { button in
Button(action: {
self.buttonSelected = button
}) {
Text("Button \(self.buttons[button])")
.padding()
.foregroundColor(.white)
.background(self.buttonSelected == button ? Color.blue : Color.green)
.clipShape(Capsule())
}
}
Button(action: {
self.buttonSelected = nil
}) {
Text("Clear Selection")
}
}
}
}

enter image description here

关于swiftui - 我怎样才能在 SwiftUI 中实现类似于 radiogroup 的一种可能选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61860758/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com