Quantm Quantm - 1 year ago 104
Swift Question

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

I created a subclass of


import UIKit

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 {

// MARK: - Overrides
override init(frame: CGRect) {
super.init(frame: frame)

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)

override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {

if isChecked {
isChecked = false
} else {
isChecked = true

return false

override func prepareForInterfaceBuilder() {

// MARK: - @IBActions

// MARK: - Functions
private func setupView() {
isUserInteractionEnabled = true

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
. Everything works. Then I added an
like this:

@IBAction func pointBtnTapped(_ sender: CheckboxButton) {
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
. Do you have any ideas?

Edit: screenshots

(couldn't embed them here. Don't know why)

Thank you!

Answer Source

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?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download