Search code examples
iosswiftuiviewuiwindowtouch-up-inside

UIButton does not respond to tap when added inside a subview on UIWindow


I have a pop-up that I need to show on UIWindow. The pop-up has 3 buttons. The pop-up is perfectly added to the window but the buttons on the pop-up does not respond to touch.

Here is my code to add pop-up to window:

let windowCount = UIApplication.shared.windows.count
UIApplication.shared.windows[windowCount-1].insertSubview(blurView, at: (UIApplication.shared.windows.last?.subviews.count)!)

Code to pop-up

func setUpHelpMenu(){

            blurView.addSubview(backView)
            _ = backView.anchorPoints(left: blurView.leftAnchor, bottom: blurView.bottomAnchor, right: blurView.rightAnchor,  leftConstant: 0, bottomConstant: 10, rightConstant: 0, widthConstant: blurView.frame.width, heightConstant: 170/812 * blurView.frame.size.height)

            backView.addSubview(resendCode)
            backView.addSubview(editPhoneNumber)
            backView.addSubview(cancel)

            _ = resendCode.anchorPoints(backView.topAnchor, centerX: backView.centerXAnchor, widthConstant: backView.frame.size.width, heightConstant: backView.frame.size.height / 3)
            _ = editPhoneNumber.anchorPoints(resendCode.bottomAnchor, centerX: backView.centerXAnchor, widthConstant: backView.frame.size.width, heightConstant: backView.frame.size.height / 3)
            _ = cancel.anchorPoints(editPhoneNumber.bottomAnchor, centerX: backView.centerXAnchor, widthConstant: backView.frame.size.width, heightConstant: backView.frame.size.height / 3 - 10)
        }

Code for the cancel button design:

let cancel: UIButton = {
        let button = UIButton()
        button.buttonTitleLabelWith(titleEdgeInsets: .zero, title: String(string: "Cancel") as NSString, lineBreakMode: .byWordWrapping, font: UIFont.systemFont(ofSize: 25/1024 * UIScreen.main.bounds.height), textColor:  UIColor.blue.withAlphaComponent(0.80))
        button.isUserInteractionEnabled = true
        button.backgroundColor = .blue
        button.addTarget(self, action: #selector(tapPopUpButtons), for: .touchUpInside)
        return button
    }()

I have checked other similar questions on SO, but none worked in my case. Let me know where I am wrong.

Any help would be appreciated.


Solution

  • Well, I found the answer. I was adding selector to the button on wrong place. Removed this code

    button.addTarget(self, action: #selector(tapPopUpButtons), for: .touchUpInside)
    

    from UIButton closure and added to viewDidLoad worked.