Floyd Resler
Floyd Resler

Reputation: 1786

iOS Swift Buttons Not Responding In View

I have written a class where a view is displayed that has a UITextView and a couple of buttons. Everything works except the buttons don't respond to a tap. Below is what I think is the relevant code in my class:

class FullPrompt:UIViewController {
    var canceledPressedCallback:(()->()?)?=nil
    var okPressedCallback:((_ txt: String)->()?)? = nil
    var popupView = UIView()
    var field = UITextView()
    var parentView = UIView()

    func prompt(_ message:String,view: UIViewController,numberInput: Bool, callback: @escaping (_ txt: String)->()) {
        prompt(message, view: view, numberInput: numberInput, callback: callback,cancelCallback: nil,defaultText: "")
    }

    func prompt(_ prompt:String,view: UIViewController,numberInput: Bool, callback: @escaping (_ txt: String)->(), cancelCallback: (()->())?,defaultText: String) {
        canceledPressedCallback=cancelCallback
        okPressedCallback=callback

        let cancelButton=UIButton(frame: CGRect(x: 10, y: y, width: 70, height: 32))
        cancelButton.setTitle("Cancel", for: .normal)
        cancelButton.addTarget(self, action: #selector(cancelButtonPressed(_:)), for: .touchUpInside)
        popupView.addSubview(cancelButton)
        let okButton=UIButton(frame: CGRect(x: 210, y: y, width: 70, height: 32))
        okButton.setTitle("Ok", for: .normal)
        okButton.setTitleColor(UIColor.blue, for: .normal)
        okButton.addTarget(self, action: #selector(okButtonPressed(_:)), for: .touchUpInside)
        popupView.addSubview(okButton)
        view.view.addSubview(popupView)
    }

    func cancelButtonPressed(_ sender: UIButton ) {
        popupView.removeFromSuperview()
        if canceledPressedCallback != nil {
            canceledPressedCallback!()
        }
    }

    func okButtonPressed(_ sender: UIButton) {
        popupView.removeFromSuperview()
        okPressedCallback!(field.text)
    }
}

What am I doing wrong?

Upvotes: 1

Views: 733

Answers (1)

Floyd Resler
Floyd Resler

Reputation: 1786

I got it figured out. My mistake was adding a view property (popupView) within my class. Since my class was a subclass of UIViewController, I needed to add my subviews to the view property of the class, not create another view. So, basically, wherever I add adding something to popupView, I just replaced it with self.view. They the buttons worked fine.

Upvotes: 1

Related Questions