2017-01-16 105 views
-2

没有要求我有两个控制器UIAlertView中的委托方法在儿童视图控制器

VC A - >ParentVC B - >Child

警报视图的委托方法即

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

VC A声明。

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

+1

将'AlertView'代码添加到您的问题。 –

+0

添加整个代码,你如何设置和调用委托方法? – iphonic

+0

FUNC showAlert(){ VAR createAccountErrorAlert:UIAlertView中= UIAlertView中() createAccountErrorAlert.delegate =自 createAccountErrorAlert.tag = sender.tag createAccountErrorAlert.accessibilityIdentifier = “ReportAbuse” createAccountErrorAlert.title = “确认” createAccountErrorAlert.message = “测试警报” createAccountErrorAlert.addButtonWithTitle( “取消”) createAccountErrorAlert.addButtonWithTitle( “OK”) createAccountErrorAlert.show() } –

回答

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

在父类VC一个

weak var delegate:alertViewDelegate() ?= nil 

实现VC B中的委托创建警报视图的委托对象,并设置委托对象在VC乙

let alertview = alertView() 
alertview.delegate = self 
0

要设置AlertView代表自我,Self意为Child,将代表改为VC A.

alertView.delegate = self.parent?.parent 
0

按照以下分步:

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

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

    var delegate: AlertViewProtocol? 
    
  3. 使用de使用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 
    
  4. 采用协议在recieving类(在这里,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-A中设置实例化VC-B对象的委托。在我而言,这是这样的:

这里,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) 
    } 

希望,这有助于你理解的代表是如何工作的过程。

相关问题