如何在Swift中重写Objective C Delegate方法

时间:2014-08-03 20:44:34

标签: syntax swift

我正在尝试在Swift中重写cocoapod的Objective-C委托协议。 cocoapod是MZTimerLabel,我试图在计时器结束时通知我的View Controller。 Xcode试图为我布置正确的语法,但我不太明白是什么要求。例如,当我正在阅读示例方法时,我无法辨别它何时显示timerLabel是否意味着键入'timerLabel'或者`timerLabel'是 my 实例的占位符MZTimerLabel。

看起来protocal告诉我调用MZTimerLabel,然后告诉它我的视图控制器中要监听哪个实例(我的实例名为brewingTimer,但我无法得到Swift语法正确。也许我应该在brewingTimer.delegate = self

中声明ViewDidLoad()
-(void)timerLabel:(MZTimerLabel*)timerLabel finshedCountDownTimerWithTime:(NSTimeInterval)countTime {
    //time is up, what should I do master?
}

My Swift尝试:

MZTimerLabel(timerLabel(brewingTimer, finshedCountDownTimerWithTime: 5)){
    //What I want to do when the timer finishes
    {self.startTimer.setTitle("Ok!", forState: .Normal)
}

我收到错误“使用未解析的标识符'timerLabel'”

我正在学习或多或少地从头开始编程Swift作为我的第一语言所以我不得不学习在Objective C中“向后”阅读代码以将其转换为Swift。另外,我不明白“countTime”是什么。我已经阅读了所有Swift文档并查看了Objective C中方法的指南,但是看到一个用Swift编写的实际Objective C方法的示例将非常有用。

1 个答案:

答案 0 :(得分:1)

您的委托功能快速变为

func timerLabel(timerLabel: AnyObject!, finshedCountDownTimerWithTime countTime: NSTimeInterval){


    self.startTimer.setTitle("Ok!", forState: .Normal)
    var yourTimerLabel =   timerLabel as? MZTimerLabel  //Downcast to MZTimerLabel
    //Now you can use yourTimerLabel as instance of MZTimerLabel

}

在您希望得到通知的viewController中实现此功能。也符合协议。 此处timerLabelMZTimerLabel

的实例

同样import您的Swift Bridging Header协议