单选单选按钮

时间:2019-01-04 11:57:18

标签: ios swift radio-button

所以我有3个按钮

override func viewDidLoad() {
    super.viewDidLoad()

    weeklyRadioButton.setImage(UIImage(named: "a"), for: .normal)
    weeklyRadioButton.setImage(UIImage(named: "b"), for: .selected)

    biWeeklyRadioButton.setImage(UIImage(named: "a"), for: .normal)
    biWeeklyRadioButton.setImage(UIImage(named: "b"), for: .selected)

    noThanksRadioButton.setImage(UIImage(named: "a"), for: .normal)
    noThanksRadioButton.setImage(UIImage(named: "b"), for: .selected)
}

@IBAction func biWeeklyRadioButtonTapped(_ sender: UIButton) {
    sender.isSelected = !sender.isSelected
    weeklyRadioButton.setImage(UIImage(named: "a"), for: .normal) . 
    // its not changing then image of the button.
    noThanksRadioButton.setImage(UIImage(named: "a"), for: .normal)
}

以及其他两个按钮的类似两个动作。

当前代码允许选择按钮。 我想知道在按钮中实现单选的方法。

所以可以说我选择了按钮1 在选择按钮2时,按钮1被取消选择

1 个答案:

答案 0 :(得分:1)

尝试以下代码。另请注意,所有按钮插座均应连接至以下操作方法。

@IBAction func anyRadioButtonTapped(_ sender: UIButton) {

    //Reset all of them first
    weeklyRadioButton.isSelected = false
    biWeeklyRadioButton.isSelected = false
    noThanksRadioButton.isSelected = false

    //Highlight associate button
    sender.isSelected = !sender.isSelected
}