【问题标题】:Getting Delegation to work with Cocoapod in Swift让委派在 Swift 中使用 Cocoapod
【发布时间】:2014-09-26 11:20:47
【问题描述】:

我正在开发一个简单的计时器应用程序。我已经正确设置了我的快速桥接头并在我的视图控制器类中声明了委托协议 class SecondViewController: UIViewController, MZTimerLabelDelegate {

然后,在viewDidLoad() 之后,我为 Delegate 实现了协议:

func timerLabel(timerLabel: AnyObject!, finshedCountDownTimerWithTime countTime: NSTimeInterval){
  self.startTimer.setTitle("Ok!", forState: .Normal)
}

我的MZTimerLabel 实例称为brewTimer。我不确定在哪里设置brewTimer.delegate = self。我有时也看到它以var delegate: myDelegate = //code here 的形式完成,我根本不明白。我能找到的在 Swift 中使用委托的所有示例都与两个视图控制器之间的转换有关,这不是我想要做的。

我想在我的应用程序中单击“开始”按钮,并让应用程序在计时器完成后更改按钮的标签。我启动计时器的计时器代码是这样的:

else {
  brewTimer.start()
  buttonSelect = 1
  startTimer.setTitle("Reset", forState: .Normal)
  //Start the circle counter graphic
  circleCounterOuter.startWithSeconds(5)
  circleCounterInner.startWithSeconds(2)
  timerLabel(brewTimer, finshedCountDownTimerWithTime:5)
}

该函数的最后一行是我调用委托的协议函数的地方,但是当我单击“开始”时,标签立即变为“确定!”而不是等待finishedCountDownTimerWithTime 的 NSTimeInterval 为 5。如果有人想知道,我正在使用 cocoapod MZTimerLabel。

【问题讨论】:

    标签: delegates swift delegation


    【解决方案1】:

    我终于通过用户对另一个问题的输入解决了这个问题。我阅读了来自Apple link 的委托,但实施仍然令人困惑。按照我的理解,我必须告诉我的 MZTimerLabel 实例在我希望委托开始的代码点“委托”。我认为这会自动发生,只要我在 View Did Load 中声明 brewTimer.delegate = self somewhere 并且我的委托代码将在我的计时器运行时执行,但显然情况并非如此。结果我不得不把brewTimer.delegate = self放在告诉我的计时器开始计数的函数的末尾(我的开始按钮函数):

    else {
        brewTimer.start()
        buttonSelect = 1
        startTimer.setTitle("Reset", forState: .Normal)
        //Start the circle counter graphic
        circleCounterOuter.startWithSeconds(5)
        circleCounterInner.startWithSeconds(2)
        //set the delegate
        brewTimer.delegate = self
    }
    

    所以在我看来,brewTimer.delegate = self 语句告诉我的“特殊”委托函数要执行。

    【讨论】:

    • 您应该只需要在viewDidLoad 中分配委托。文档有误,正确的委托是 func timerLabel(timerLabel: MZTimerLabel!, finshedCountDownTimerWithTime countTime: NSTimeInterval)
    猜你喜欢
    • 2015-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    • 1970-01-01
    • 2022-08-18
    • 2020-10-16
    • 1970-01-01
    相关资源
    最近更新 更多