用Swift语言代表
我有两个控制器,我需要调用function的第一个控制器到第二个控制器:在第二个控制器我创build了协议和init委托类:
protocol testProtocol { func testDelegate() // this function the first controllers } class SecondViewController: UIViewController { var delegate: testProtocol? .... } @IBAction func testDelegateClicked(sender : AnyObject) { delegate?.testDelegate() }
第一控制器
class ViewController:UIViewController,testProtocol {
var secondController: SecondViewController = SecondViewController() override func viewDidLoad() { super.viewDidLoad() secondController.delegate = self } func testDelegate() { println("Hello delegate") }</pre>
但function没有被调用
我将假设你正在使用故事板。 如果我是正确的,那么你的问题是,你的第一个控制器中创build的secondController
控制器,是不是你正在展示的实际。 您将需要在prepareForSegue:
设置secondController
prepareForSegue:
第二控制器
不变
第一控制器
class ViewController: UIViewController, testProtocol { // you will want to add the ? since this variable is now optional (ie 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; } }