简体   繁体   English

不带prepareForSegue的Swift代表

[英]Swift Delegate without prepareForSegue

I'm new to swift and ios development. 我是swiftios开发的新手。 I have two classes and want them to connect. 我有两个课程,希望他们能够联系。 I'm not using the prepareForSegue . 我没有使用prepareForSegue This is what I have, something must be wrong somewhere. 这就是我所拥有的,某处一定有问题。

protocol TimeDelegate{
 func timerDidFinish()
}


class Timer: UIViewController {

// this is where we declare our protocol
var delegate:TimeDelegate?

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func timeFired(sender: UIButton){

    delegate?.timerDidFinish()

}

}


import UIKit


class ViewController: UIViewController, TimeDelegate {

var timer:Timer = Timer()

override func viewDidLoad() {
    super.viewDidLoad()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func timerDidFinish(){

    println("Delegate is working")
}

}

For some reason, timerDidFinish is not firing. 由于某些原因, timerDidFinish没有触发。

From your explanation i gather that the two UIViewControllers are not linked in any way. 从您的解释中,我得知两个UIViewControllers没有以任何方式链接。

When you click the button to fire the @IBAction func timeFired(sender: UIButton){..} function, you will be in Timer UIViewController. 当您单击按钮以触发@IBAction func timeFired(sender: UIButton){..}函数时,您将位于Timer UIViewController中。

Then when are you instantiating ViewController ? 然后,何时实例化ViewController Without instantiating it the delegate will never be set. 如果不实例化它,则将永远不会设置委托。

If you just want to call the timerDidFinish() func and want nothing else to do with ViewController then do this: 如果您只想调用timerDidFinish()函数,并且不想与ViewController进行任何其他操作,请执行以下操作:

class Timer: UIViewController {

var delegate:TimeDelegate?

override func viewDidLoad() {
super.viewDidLoad()
var vc = ViewController()
self.delegate = vc

}

Then your function will be called. 然后将调用您的函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM