在创建自定义UIButton类时将UIButton状态设置为selected

时间:2015-04-29 17:26:38

标签: ios swift uibutton

我的UIButton已经创建,并且它具有我想要的状态的颜色。

但是,当我点击它时,它不会保持选中状态。

我正在阅读的所有代码都会在IB操作后解决View Controller中按钮的状态。我还不了解touchesBegan方法。

我必须重复这14次,并希望避免为每个人设置这个..

编辑:代码:

class AppointmentDatePickerAMButton: UIButton {
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.setTitleColor(UIColor.grayColor(), forState: UIControlState.Normal)
        self.setTitleColor(UIColor.redColor(), forState: UIControlState.Highlighted)
        self.setTitleColor(UIColor.blueColor(), forState: UIControlState.Selected)


    }
}

1 个答案:

答案 0 :(得分:0)

将此添加到UIButton:

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    super.touchesBegan(touches, withEvent: event)
    self.highlighted = true

}

override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
    super.touchesEnded(touches, withEvent: event)
    self.selected = !self.selected
    self.highlighted = false
}