自定义UIButton保持选中状态并更改颜色

时间:2015-07-05 03:47:32

标签: ios swift uibutton

有没有办法在点击时更改自定义UIButton的颜色,让它保持不变直到再次点击?目前我覆盖了drawRect以创建自定义按钮,但不知道从那里去哪里。

编辑:

class DayButtons: UIButton {

    var isPressed: Bool = false

    var color = UIColor.whiteColor()

        override func drawRect(rect: CGRect) {
        let cornerR = CGFloat(5)       
        var path = UIBezierPath(roundedRect: rect, cornerRadius: cornerR)
        color.setFill()
        path.fill()
    }
}

1 个答案:

答案 0 :(得分:2)

不确定您在哪里设置按钮颜色,但更改按钮颜色的代码如下所示:

yourButton.backgroundColor = UIColor.blueColor() // this would make the button color blue.

您可以在viewDidLoad中以编程方式设置按钮颜色,并在调用IBAction时进行更改。例如,您可以在IBAction

中添加此行
yourButton.backgroundColor = UIColor.redColor()

您可能会发现这篇文章有用:

Change button background color using swift language

更新

没有看到代码,我不确定你要做什么。您可以使用以下代码更改rect的填充: UIColor.whiteColor().setFill()

单击按钮时可以重绘矩形,并将颜色绑定到Bool。这样的东西会进入与你的按钮绑定的IBAction以切换状态:

if self.myCondition == true { 
    self.myCondition = false
    } else { 
    self.myCondition = true
}

在用于创建rect的代码中,您可以执行以下操作:

if self.myCondition == true { 
    UIColor.greenColor().setFill()
    } else { 
    UIColor.redColor().setFill()
}
相关问题