"addTarget" action function of UIButton not called (strikethrough)?

2k Views Asked by At

I have a UIButton within a UITableViewCell. When I call addTarget on the button and attempt to put a function in, the autocomplete has the function crossed out with a white line (see first image). Xcode still allows me to put the function in and run the app; however, when the button is tapped the function isn't called.

enter image description here

Button initialization:

private let infoButton: UIButton = {
        let button = UIButton()
        button.backgroundColor = .clear
        button.adjustsImageWhenHighlighted = false
        button.setImage(Images.sizeGuide, for: .normal)
        button.addTarget(self, action: #selector(infoButtonPressed(_:)), for: .touchUpInside)
        return button
    }()

Function (infoButtonPressed):

@objc private func infoButtonPressed(_ sender: UIButton) {
        print("Button Pressed")
    }

Because I reuse this cell multiple times and only one of these cells needs to have this button, I have a variable that dictates whether or not to show the button:

var hasInfoButton: Bool = false {
        didSet {
            if hasInfoButton {
                setupInfoButton()
            }
        }
    }

The function that is called above simply sets up the button using autoLayout. Something to mention: when I tried calling addTarget in this function, the app crashed with Unrecognized selector sent to instance...

The tableView in which this is embedded in is only static and displays data. Therefore, allowSelection and allowsMultipleSelection are both set to false.

Does anyone have a solution to this?

1

There are 1 best solutions below

0
On

You shouldn't need (_ sender: UIButton) the method should just be:

@objc func infoButtonPressed() {
    print("button pressed")
}

EDIT: The button initializer is also a little strange. The way I generally go about this kind of thing is like this:

let button = UIButton()

private func configureButton() {
        button.backgroundColor = .clear
        button.adjustsImageWhenHighlighted = false
        button.setImage(Images.sizeGuide, for: .normal)
        button.addTarget(self, action: #selector(infoButtonPressed(_:)), for: .touchUpInside)
}

Then call configureButton() in viewDidLoad()