Maksym Svitlovskyi
Maksym Svitlovskyi

Reputation: 11

UIButton doesn't work in child view controller

UIButton gestures doesn't recognize in child view controller. UIButton add targer work (button get target action) User interaction is turned on everywhere, button size is okay. I try to set childVC as main, and then all work good, debug view hierarchy said that button view over other elements. IDK where is problem. I can provide more code, just tell me.

Add target code:

        view.buttonOfLanguageFromTranslate.addTarget(self, action: #selector(self.openDetailView(_:)), for: .touchDown)

Add child VC code:

    let childVC = ChildVC()
    view.addSubview(childVC.view)
    
    self.addChild(childVC)
    childVC.didMove(toParent: self)
    
    childVC.view.translatesAutoresizingMaskIntoConstraints = false
    self.view.isUserInteractionEnabled = true
    self.childVC = childVC

Button initialization:

    var button: UIButton = {
    let button = UIButton()
    button.setTitle("Title", for: .normal)
    button.setTitleColor(.black, for: .normal)
    button.setTitleColor(.green, for: .selected)
    button.translatesAutoresizingMaskIntoConstraints = false
    return button
}()

Upvotes: 0

Views: 439

Answers (2)

Vlad Grigorov
Vlad Grigorov

Reputation: 11378

I had the same issue. In my case the buttons on the child view controller did not work because I had forgotten to add that view controller as a child to its parent view controller.

In other words, I missed this line:

addChild(childVC)

Upvotes: 0

Maksym Svitlovskyi
Maksym Svitlovskyi

Reputation: 11

The problem was with

        childVC.translatesAutoresizingMaskIntoConstraints = false

(in mainVC) When i remove it, childVC recognise my tap and i dont set additional size for childVC, view of childVC is display correct but not childVC. (as i think)

Upvotes: 0

Related Questions