Search code examples
iosswiftuiviewcontrollerdelegatesxib

how to notify a UIViewController that a button was clicked in a xib file using a delegate in swift?


I'm a bit stuck. I have a UIViewController and a custom pop.xib that extends UIView. pop.xib is connected to pop.swift. In the UIViewController a button makes the .xib file pop up.

And in pop.xib there is a button that is clicked to send some data to the database.

But when that button is clicked in pop.xib to send data I want the UIViewController to

a) know when the @IBAction func sendDataToDbAction(_ sender: Any) is clicked and

b) when the if statement returns false from inside sendDataToDbAction then present an alert on the UIViewController

//pop.swift

     class Pop: UIView {

            @IBOutlet var delegate: AnswerDelegate?

            @IBAction func sendDataToDbAction(_ sender: Any)
            {
                     if(answer == false)
                     {
                          don't send to db
                          alert pops up saying answer is false
                     }
                     else
                     {

                     }

            }
         }

I've set up a delegate in pop.swift

//pop.swift

@objc protocol AnswerDelegate {

    func isCorrectAnswer()
}



//UIViewController

extension UIViewController:AnswerDelegate{

//set the pop.xib delegate to self
// implement func isCorrectAnswer

}

I'm just not sure how I can use the delegate to do what I want.

Thanks.


Solution

  • Check this out, you can do it like this.

    Pop.swift

    @objc protocol AnswerDelegate {
        func isCorrectAnswer()
    }
    
    class Pop: UIView {
    
        var answerDelegate: AnswerDelegate?
    
        class func instanceFromNib() -> Pop {
            return UINib(nibName: "Pop", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! Pop
        }
    
        @IBAction func sendDataToDbAction(_ sender: Any)
        {
            if(answer == false) {
                //Alert
            }
            else {
                answerDelegate?.isCorrectAnswer()
            }
        }
    }
    

    Controller:

    class ViewController: UIViewController, AnswerDelegate {
    
        func isCorrectAnswer() {
    
        }
    
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
    
            let popView = Pop.instanceFromNib()
            popView.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
            popView.answerDelegate = self
    
            self.view.addSubview(popView)
        }
    }