我是swiftios开发的新手。我有两个班,希望他们能够联系。我没有使用prepareForSegue。这就是我所拥有的,某处一定有问题。

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

}

由于某些原因, timerDidFinish 无法启动。

最佳答案

从您的解释中,我得知两个UIViewControllers没有以任何方式链接。

当您单击按钮触发@IBAction func timeFired(sender: UIButton){..}函数时,您将在Timer UIViewController中。

然后,何时实例化ViewController?如果不实例化它,则将永远不会设置委托。

如果您只想调用timerDidFinish()函数,而又不想与ViewController无关,请执行以下操作:

class Timer: UIViewController {

var delegate:TimeDelegate?

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

}

然后您的函数将被调用。

10-08 06:11