我有两个控制器,我需要调用第一个控制器到第二个控制器的功能:在第二个控制器中,我在类中创建了协议和初始化委托:
protocol testProtocol { func testDelegate() // this function the first controllers } class SecondViewController: UIViewController { var delegate: testProtocol? .... } @IBAction func testDelegateClicked(sender : AnyObject) { delegate?.testDelegate() }
第一控制人
ViewController类:UIViewController,testProtocol { var secondController: SecondViewController = SecondViewController() override func viewDidLoad() { super.viewDidLoad() secondController.delegate = self } func testDelegate() { println("Hello delegate") }</pre>
但是函数没有被调用
我将假设您正在使用情节提要。如果我是正确的话,那么您的问题是,secondController在您的“第一个控制器”中创建的“”不是您要演示的实际内容。您将需要设置secondController你的prepareForSegue:
secondController
prepareForSegue:
不变的
class ViewController: UIViewController, testProtocol { // you will want to add the ? since this variable is now optional (i.e. can be nil) var secondController: SecondViewController? // don't assign it a value yet // ... // implementation of the protocol func testDelegate() { println("Hello delegate") } // your prepare for segue override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) { // get the controller that storyboard has instantiated and set it's delegate secondController = segue!.destinationViewController as? SecondViewController secondController!.delegate = self; } }