SwiftUI:如何用单个Bool变量实现多按钮中单个按钮标签切换
解决SwiftUI单按钮样式独立切换问题
不用声明多个Bool变量,你可以用一个可选类型的变量来记录当前选中的按钮标识,这样就能精准控制单个按钮的样式变化,而不是全部按钮同步切换。
优化后的代码示例
struct SizeSelectorView: View { // 用可选字符串存储当前选中的尺码,初始无选中状态 @State var selectedSize: String? var body: some View { HStack { Text("Size") .fontWeight(.bold) Spacer() Button { // 点击时切换选中状态:已选中则取消,未选中则标记为当前尺码 selectedSize = selectedSize == "US" ? nil : "US" } label: { Text("US") .foregroundColor(selectedSize == "US" ? .black : .gray.opacity(0.5)) .fontWeight(.bold) } Button { selectedSize = selectedSize == "UK" ? nil : "UK" } label: { Text("UK") .foregroundColor(selectedSize == "UK" ? .black : .gray.opacity(0.5)) .fontWeight(.bold) } Button { selectedSize = selectedSize == "EU" ? nil : "EU" } label: { Text("EU") .foregroundColor(selectedSize == "EU" ? .black : .gray.opacity(0.5)) .fontWeight(.bold) } } } }
进一步优化:提取自定义按钮组件
如果后续需要扩展更多尺码,把按钮抽成自定义组件能大幅减少重复代码:
struct SizeButton: View { let title: String @Binding var selectedSize: String? var body: some View { Button { selectedSize = selectedSize == title ? nil : title } label: { Text(title) .foregroundColor(selectedSize == title ? .black : .gray.opacity(0.5)) .fontWeight(.bold) } } } // 使用自定义组件的主视图 struct SizeSelectorView: View { @State var selectedSize: String? var body: some View { HStack { Text("Size") .fontWeight(.bold) Spacer() SizeButton(title: "US", selectedSize: $selectedSize) SizeButton(title: "UK", selectedSize: $selectedSize) SizeButton(title: "EU", selectedSize: $selectedSize) } } }
原理说明
- 用
selectedSize变量记录当前选中的按钮标识(这里用尺码字符串),替代单个Bool变量,能精准区分不同按钮的选中状态。 - 每个按钮的点击逻辑只修改自身对应的选中状态,样式判断也只对比自身标识,实现独立的样式切换。
内容的提问来源于stack exchange,提问作者hussein
相关产品推荐
相关产品推荐

