简体   繁体   中英

UIAlertview Delegate Method not calling in Child View Controller

I have two controllers

VC A -> Parent and VC B -> Child

Alert view delegate method ie

func alertView(View: UIAlertView!, clickedButtonAtIndex buttonIndex: Int){}

is declared in VC A .

When i display alert from VC B delegate method is not called on alert button clicked.

protocol alertViewDelegate:class {
    func alertView(View: UIAlertView!, clickedButtonAtIndex buttonIndex: Int)
}

Create an alert view delegate object in parent class VC A

weak var delegate:alertViewDelegate() ?= nil

Implement the delegate in VC B and Set the delegate object in VC B

let alertview = alertView()
alertview.delegate  = self

您将AlertView委托设置为 self,Self 表示Child ,将委托更改为 VC A。

alertView.delegate = self.parent?.parent

Follow these step by step:

  1. Create a protocol in your VC-B as:

     protocol AlertViewProtocol:class { func alertView(View: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) }
  2. Add a var in your VC-B class as:

     var delegate: AlertViewProtocol?
  3. Use the delegate in any class method of VC-B to send the data to the receiving method (ie any method of VC-A), which is any method that adopts the protocol. Follow this pattern to use the delegate:

     delegate?.alertView(View: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) // Above statement is like a method calling (on delegate var), use your parameters accordingly
  4. Adopt the protocol in your recieving class (here, VC-A):

     class ViewControllerA: UIViewController, AlertViewProtocol { ... ... }
  5. Implement the delegate method in VC-A:

     func alertView(View: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) { // Do your stuff // when you click on the designated button in your VC-B, this method will be invoked }
  6. Set the delegate in VC-A where you are instantiating the VC-B object. In my case this is like:

Here, vcb?.delegate = self is very important. If you forget to set the delegate property of the object with self the delegation process won't work.

    @IBAction func showVCB(sender: AnyObject) {
        let vcb: ViewControllerB? = self.storyboard?.instantiateViewControllerWithIdentifier("viewcontrollerB") as? ViewControllerB
        vcb?.delegate = self
        self.presentViewController(vcb!, animated: true, completion: nil)
    }

Hope, this helps you for understanding the process of how the delegates work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM