Home > Mobile >  IBAction not firing for button in subview
IBAction not firing for button in subview

Time:05-31

I have a view that has two subviews. One view, the AnswerView, is to group elements, but also hide and unhide them. Inside this AnswerView is another subview called AnswerButtons that just contains two buttons and the main purpose of the view is to help with formatting. I only have a single view controller right now which is for the top parent view.

When I click one of the "yes" or "no" buttons on the innermost subview the IBAction event doesn't get fired. I tried putting print statements in there and break points and never reach them. If however I move the buttons to the top-level view everything works as expected.

Controller code:

class ViewController: UIViewController {

@IBOutlet weak var revealButton: UIButton!
@IBOutlet weak var answerView: UIView!
@IBOutlet weak var yesButton: UIButton!
@IBOutlet weak var noButton: UIButton!
@IBOutlet weak var answerText: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    answerView = view.viewWithTag(42);
}

@IBAction func RevealPressed(_ sender: Any) {
    answerView.isHidden = false;
    revealButton.isHidden = true;
}
@IBAction func yesPressed(_ sender: Any) {
    print("YES PRESSED!!!")
    answerView.isHidden = true;
    revealButton.isHidden = false;
}

@IBAction func testButton(_ sender: Any) {
    yesButton.setTitle("changed", for: UIControl.State.normal)
}

@IBAction func NoPressed(_ sender: Any) {
    answerView.isHidden = true;
    revealButton.isHidden = false;
}

}

Storyboard and view hierarchy: Storyboard

CodePudding user response:

Typically this happens when the button is outside the bounds of its superview (Answer View or Answer Buttons). Such a button cannot be tapped.

Usually this happens because the superview has no size. A superview without size has subviews that are visible but untouchable, which is confusing.

This would presumably be because of a mistake with your constraints. You can track this down with the View Debugger.

Another possibility is that a superview has its isUserInteractionEnabled switched off. This again would make subviews untouchable.

See also my https://www.biteinteractive.com/sherlock-holmes-and-the-mystery-of-the-untappable-button/ It gives some code tools for tracking down this sort of thing.

  • Related