我的UIButton已经创建,它具有我想要的状态的颜色。
但是,当我单击它时,它不会保持选中状态。
我正在阅读的所有代码都涉及IB操作后视图控制器中按钮的状态。我也不了解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)
}
}
您要做的是为按钮添加目标操作,将按钮实例传递给该方法,并在其上设置sender.selected = YES
(如果仅选择)或sender.selected = !sender.selected
(如果需要打开/关闭行为)。在代码中,您定义了所选状态的外观,然后只需设置对该状态的控制即可。请记住,按钮可以同时组合多个状态(例如高亮显示和选中)。
将其添加到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
}