1、自定义一个RadioButton组件的View视图
struct RadioButton:view{
let selfID: string
let selectedID: String
init(selfID: String,selectedID: String){
self.selfID= selfID
self.selectedID=selectedID
}
var body: some View{
Button(action:{
self.selectedID=self.selfID
},label:{
HStack(alignment:.center,spacing:12,content:{
Text(self.id)
.frame(width: 60,height:50)
.background(Color.blue)
.foregroundColor(self.selectedID == self.selfID? Color.blue : Color.black)
.background(Color.blue)
.cornerRadius(10)//设置按钮的圆角
})
})
}
}
selfID:当前RadioButton自身ID
selectedID:当前被选中的RadioButton的ID
Button:RadioButton被点击时的回调函数,作用把selfID赋值给selectedID
2、在主View视图里面对上定义的RadioButtonView组件进行调用
let items:[String]=["色盘循环","色温循环",“亮度循环",“闪烁"]
@State var selectedID = ""
HStackt{
ForEach(items,id:\.self){item in
RadioButton(id: item,selectedID: self,selectedID)
}
}