我创建了 UIButton
的子类:
import UIKit
@IBDesignable
class CheckboxButton: UIButton {
@IBInspectable var checkboxBackgroundColor: UIColor = Project.Color.baseGray
@IBInspectable var textColor: UIColor = Project.Color.mainDarkText
@IBInspectable var checkboxHighlightedBackgroundColor: UIColor = Project.Color.main
@IBInspectable var highlightedTextColor: UIColor = Project.Color.mainBrightText
// MARK: - Properties
var isChecked: Bool = false {
didSet {
changeState()
}
}
// MARK: - Overrides
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
if isChecked {
isChecked = false
} else {
isChecked = true
}
return false
}
override func prepareForInterfaceBuilder() {
changeState()
}
// MARK: - @IBActions
// MARK: - Functions
private func setupView() {
isUserInteractionEnabled = true
changeState()
}
private func changeState() {
if isChecked {
backgroundColor = checkboxHighlightedBackgroundColor
self.setTitleColor(highlightedTextColor, for: .normal)
} else {
backgroundColor = checkboxBackgroundColor
self.setTitleColor(textColor, for: .normal)
}
}
}
现在我在 Storyboard 中添加了一个按钮,并赋予它 CheckboxButton
类。一切正常。然后我添加了一个 IBAction
,如下所示:
@IBAction func pointBtnTapped(_ sender: CheckboxButton) {
print("tapped")
selectButton(withNumber: sender.tag)
}
但这不起作用(没有打印出来)。它适用于普通按钮,但如果按钮是 CheckboxButton
的子类,则无效。你有什么想法吗?
编辑:截图 https://www.dropbox.com/s/ewicc349ag9l6y2/Screenshot%202016-10-06%2023.41.39.png?dl=0
https://www.dropbox.com/s/vxevzscueproivc/Screenshot%202016-10-06%2023.42.33.png?dl=0 (无法将它们嵌入此处。不知道为什么)
谢谢!
最佳答案
您通过覆盖 beginTracking()
并始终返回 false 破坏了 UIButton
。这会对按钮进行洗脑,使其认为它永远不会被点击。
你的意图是什么?在任何情况下,在那里返回 true
,您的代码将触发 @IBAction
。
编辑:您通过使用用于高度自定义行为(例如非矩形按钮)的低级方法来考虑问题。你只需要:
关于ios - 内部修饰 (@IBAction) 不适用于 UIButton 子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39905830/