Wouter Vanacht Wouter Vanacht - 1 year ago 198
iOS Question

Adding target to UIButton does not work

I'm new to iOS programming and am following the Apple 'Start Developing' course to get to know how iOS app development works. I'm at the point of adding a view to my storyboard. This new view contains a button which I create programmatically.

The app layout, the highlighted part is the added view.

App layout, highlighted part is the view

I'm trying to add an action to this button but it just won't work.

My code in


// MARK: Button Action
func ratingButtonTapped(button: UIButton) {
print("Button pressed")

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

let button = UIButton(type: .system)
button.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
button.backgroundColor = UIColor.red
button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(button:)), for: .touchUpInside)

Now my screen when I run the app:

running screen

Clicking the red square doesn't print anything in the output window. I also added a breakpoint in the action function but it never breaks.

Answer Source

The problem is that the Rating Control has no width / height constraints. Therefore, being inside a stack view, its width and height are reduced to zero. Therefore the button ends up outside the Rating Control (because the latter has zero size; everything is outside it). A subview outside its superview is non-interactive.

Just give the rating control a width constraint and a height constraint and all will be well.

You could easily have detected this by giving the rating control, temporarily, some background color. You would then have seen instantly when running the app that the rating control was missing from the layout.

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