Quantm Quantm - 1 month ago 20
Swift Question

touch up inside (@IBAction) does not work with UIButton subclass

I created a subclass of

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)
}
}
}


Now I added a button inside the storyboard and gave it the class
CheckboxButton
. Everything works. Then I added an
IBAction
like this:

@IBAction func pointBtnTapped(_ sender: CheckboxButton) {
print("tapped")
selectButton(withNumber: sender.tag)
}


But this doesn't work (nothing prints out). It works with a normal button, but not if the button is the subclass
CheckboxButton
. Do you have any ideas?

Edit: screenshots
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
(couldn't embed them here. Don't know why)

Thank you!

Answer

You broke UIButton by overriding beginTracking() and always returning false. This brainwashes the button into thinking it's never being clicked.

What was your intent there? In any case, return true there and your code will fire the @IBAction.

EDIT: You're overthinking the issue by using a low-level method meant for highly customized behavior such as non-rectangular buttons. You just need:

How to use UIButton as Toggle Button?

Comments