Swift 语言的委托 [英] Delegate in Swift-language
本文介绍了Swift 语言的委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个控制器,我需要调用第一个控制器到第二个控制器的功能:在第二个控制器中,我在类中创建了协议和初始化委托:
I have two controllers and i need call up function the first controller to second controller: In second controller I have created protocol and init delegate in class:
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 {
First Controller
但是函数没有被调用
推荐答案
我将假设您正在使用故事板.如果我是对的,那么您的问题是在您的第一个控制器中创建的 secondController
不是您所展示的实际控制器.您需要在 prepareForSegue:
I am going to make an assumption you are using storyboards. If I am correct, then your issue is that your secondController
, created in your First Controller, is not the actual one you are presenting. You will need to set secondController
in your 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;
}
}
这篇关于Swift 语言的委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文