Swift中如何实现单选按钮与选择器语句的关联?
看起来你在实现ISRadioButton的单选逻辑,我帮你把代码补全并梳理清楚关联逻辑,这样就能完美实现单选按钮和选择逻辑的绑定啦:
首先,你需要把同组的单选按钮关联起来,这样点击其中一个时,其他按钮会自动取消选中状态。我们以性别选择为例,先完成按钮的创建与组关联:
// 创建Male单选按钮 let button7: ISRadioButton = ISRadioButton(frame: CGRect(x: 60, y: 75, width: 70, height: 35)) button7.addTarget(self, action: #selector(buttonClicked4), for: .touchUpInside) button7.setTitle("Male", for: .normal) button7.setTitleColor(UIColor.black, for: .normal) button7.titleLabel?.font = UIFont.boldSystemFont(ofSize: 12) // 创建Female单选按钮(你的原有代码) let button8: ISRadioButton = ISRadioButton(frame: CGRect(x: 140, y: 75, width: 70, height: 35)) button8.addTarget(self, action:#selector(buttonClicked4), for: .touchUpInside) button8.setTitle("Female", for: .normal) button8.setTitleColor(UIColor.black, for: .normal) button8.titleLabel?.font = UIFont.boldSystemFont(ofSize: 12) // 关键:将两个按钮加入同一个单选组,实现互斥选中 button8.otherButtons = [button7] button7.otherButtons = [button8] // 将按钮添加到视图显示 view.addSubview(button7) view.addSubview(button8)
单选按钮点击事件的完整处理
接下来补全你的buttonClicked4方法,实现选中后的逻辑处理:
@objc func buttonClicked4(_ isRadioButton: ISRadioButton){ // 切换当前按钮的选中状态(单选模式下,同组其他按钮会自动取消选中) isRadioButton.isSelected = !isRadioButton.isSelected // 根据选中的按钮执行对应业务逻辑 switch isRadioButton { case button7: print("用户选择了Male") // 这里写Male选项对应的操作,比如更新用户信息、刷新界面等 case button8: print("用户选择了Female") // 这里写Female选项对应的操作 default: break } // 如果你需要支持多选模式,可以保留这段逻辑(单选场景下可忽略) // if isRadioButton.multipleSelectionEnabled { // for radioButton in isRadioButton.otherButtons { // // 多选模式下的自定义处理,比如允许同时选中多个按钮 // } // } }
额外小技巧
如果需要页面加载时默认选中某个选项,只需要在按钮初始化后添加一行代码:
// 默认选中Male button7.isSelected = true
内容的提问来源于stack exchange,提问作者Umair Ahmad
相关产品推荐
相关产品推荐

