内部修饰(@IBAction)不适用于UIButton子类

时间:2016-10-06 21:22:49

标签: ios swift uibutton

我创建了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)
    }
}
 }

现在我在故事板中添加了一个按钮,并为其提供了课程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 (不能把它们嵌在这里。不知道为什么)

谢谢!

1 个答案:

答案 0 :(得分:1)

您通过覆盖UIButton并且始终返回false来中断beginTracking()。这个脑子按下按钮,认为按钮从未被点击过。

你的意图是什么?在任何情况下,请返回true,您的代码将触发@IBAction

编辑:您通过使用针对高度自定义行为(例如非矩形按钮)的低级方法来过度思考问题。你只需要:

How to use UIButton as Toggle Button?