UIAlertview Delegate Method not calling in Child View Controller

拥有回忆 提交于 2019-12-13 11:01:50

问题


I have two controllers

VC A -> Parent and VC B -> Child

Alert view delegate method i.e

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.


回答1:


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



回答2:


You are setting AlertView delegate to self, Self means Child, Change delegate to VC A.

alertView.delegate = self.parent?.parent



回答3:


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 (i.e. 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.



来源:https://stackoverflow.com/questions/41670544/uialertview-delegate-method-not-calling-in-child-view-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!