Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
467 views
in Technique[技术] by (71.8m points)

ios - Delegate in Swift-language

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()
        }

First Controller

        class ViewController: UIViewController, testProtocol {

        var secondController: SecondViewController = SecondViewController()

        override func viewDidLoad() {
            super.viewDidLoad()

            secondController.delegate = self
        }
        func testDelegate() {
            println("Hello delegate")
        }</pre>

But function not getting called

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

Second Controller

Unchanged

First Controller

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;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...