在选择/取消选择UIButton之间切换

时间:2016-09-22 09:34:08

标签: ios swift uibutton

我有一个按钮,我想在点击(选择)时更改背景颜色和文本,并在再次点击时将其恢复到原始状态(取消选择)。我能够选择它,但我无法取消选择它。我研究了SO,我在if-else部分的代码中遇到错误

   @IBAction func btn1Pressed(_ sender: AnyObject) {
        sender.setTitleColor(UIColor.blue, for: UIControlState.normal)
        (sender as! UIButton).backgroundColor = UIColor.green

        if sender.isSelected {
            sender.selected = false
        }
        else {
            sender.selected = true
        }
    }

7 个答案:

答案 0 :(得分:0)

更改storyboard中所选按钮的背景颜色,如下所示state config选择selected,然后更改背景颜色,并将普通按钮的默认值设为coustomize。

enter image description here

并在行动中使用

(sender as! UIButton).selected = !(sender as! UIButton).selected

答案 1 :(得分:0)

试试这个

 @IBAction func btn1Pressed(sender: UIButton) {


    if sender.selected {
        sender.selected = false
        sender.setTitleColor(UIColor.redColor(), forState: .Normal)
         sender.backgroundColor = UIColor.blackColor()


    }
    else {
        sender.selected = true
        sender.setTitleColor(UIColor.redColor(), forState: .Selected)
        sender.backgroundColor = UIColor.blackColor()
    }
}

答案 2 :(得分:0)

听起来像UISwitch就是你要找的东西。试一试,而不是浪费时间实现已经存在的东西。

答案 3 :(得分:0)

试试这个:

@IBAction func btn1Pressed(_ sender: AnyObject) {

    guard let button = sender as? UIButton else { return }

    if !button.isSelected {
        button.isSelected = true
        button.setTitleColor(UIColor.blue, for: UIControlState.normal)
        button.backgroundColor = UIColor.green
    }
    else {
        button.isSelected = false
        button.setTitleColor(UIColor.green, for: UIControlState.normal)
        button.backgroundColor = UIColor.blue
    }
}

答案 4 :(得分:0)

请首先尝试此代码,您需要创建按钮的操作和属性,如

@IBOutlet var btn_ButtonPressed: UIButton!

然后行动。

    @IBAction func click_ButtonPressed(_ sender: Any) {
  if !sender.isSelected() {
    sender.selected = true
    btn_ButtonPressed.setTitleColor(UIColor.red, forState: .normal)
    btn_ButtonPressed.backgroundColor = UIColor.yellow
    }
else {
    sender.selected = false
    btn_ButtonPressed.setTitleColor(UIColor.yellow, forState: .normal)
    btn_ButtonPressed.backgroundColor = UIColor.red
    }
}

答案 5 :(得分:0)

this one worked fine for me! // @IBAction func buttonColorChanger(sender : UIButton ) {

if button.isSelected == false
{

    button.backgroundColor = UIColor.purple
    print("selected")

    button.setTitle("selected", for: .normal)
    button.setTitleColor(UIColor.white, for: .normal)
     button.isSelected = true
}else{

    button.backgroundColor = UIColor.white
    print("unselected")
    button.isSelected = false

}
       }

答案 6 :(得分:0)

更清洁的方法是:

@objc private func buttonTapped(_ sender: UIButton) {
    sender.isSelected.toggle()

    if selected {
        // Setup appearance for selected state.
    } else {
        // Setup appearance for deselected state.
    }
}