UIAlertview委托方法不在子视图控制器中调用
我有两个控制器
VC A
– > Parent
和VC B
– > Child
警报视图委托方法即
func alertView(View: UIAlertView!, clickedButtonAtIndex buttonIndex: Int){}
在VC A
声明。
当我显示来自VC B
警报委托方法不会被警告button点击调用。
protocol alertViewDelegate:class { func alertView(View: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) }
在父类VC A中创build一个警报视图委托对象
weak var delegate:alertViewDelegate() ?= nil
在VC B中实现委托并在VC B中设置委托对象
let alertview = alertView() alertview.delegate = self
您将AlertView
设置为self,Self代表Child
,将AlertView
更改为VC A.
alertView.delegate = self.parent?.parent
按照以下步骤:
-
在VC-B中创build一个协议为:
protocol AlertViewProtocol:class { func alertView(View: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) }
-
在VC-B类中添加一个var ,如下所示:
var delegate: AlertViewProtocol?
-
使用委托在VC-B的任何类方法中将数据发送到接收方法(即VC-A的任何方法),这是任何采用该协议的方法。 按照这种模式使用委托:
delegate?.alertView(View: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) // Above statement is like a method calling (on delegate var), use your parameters accordingly
-
在你的接收类(在这里,VC-A)采用协议:
class ViewControllerA: UIViewController, AlertViewProtocol { ... ... }
-
在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 }
-
在实例化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) }
希望这可以帮助你理解代表如何工作的过程。