繁体   English   中英

UIAlertview 委托方法不在子视图控制器中调用

[英]UIAlertview Delegate Method not calling in Child View Controller

我有两个控制器

VC A -> ParentVC B -> Child

警报视图委托方法即

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

VC A声明。

当我显示来自VC B委托方法的警报时,不会在单击警报按钮时调用。

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

在父类 VC A 中创建警报视图委托对象

weak var delegate:alertViewDelegate() ?= nil

在 VC B 中实现委托并在 VC B 中设置委托对象

let alertview = alertView()
alertview.delegate  = self

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

alertView.delegate = self.parent?.parent

请按以下步骤操作:

  1. 在 VC-B 中创建一个协议为:

     protocol AlertViewProtocol:class { func alertView(View: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) }
  2. 在 VC-B 类中添加一个var为:

     var delegate: AlertViewProtocol?
  3. 在VC-B的任何类方法中使用delegate将数据发送到接收方法(即VC-A的任何方法),即任何采用该协议的方法。 按照此模式使用委托:

     delegate?.alertView(View: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) // Above statement is like a method calling (on delegate var), use your parameters accordingly
  4. 在您的接收类中采用该协议(此处为 VC-A):

     class ViewControllerA: UIViewController, AlertViewProtocol { ... ... }
  5. 在 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. 在实例化 VC-B 对象的 VC-A 中设置委托。 就我而言,这就像:

在这里, vcb?.delegate = self很重要。 如果您忘记使用self设置对象的委托属性,则委托过程将不起作用。

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

希望,这有助于您了解代表如何工作的过程。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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