syntax - 如何在 Swift 中重写 Objective C 委托(delegate)方法

标签 syntax swift

我正在尝试用 Swift 重写 cocoapod 的 Objective-C 委托(delegate)协议(protocol)。 cocoapod 是 MZTimerLabel,我试图在计时器结束时通知我的 View Controller 。 Xcode 试图为我设计正确的语法,但我不太明白要求的是什么。例如,当我阅读示例方法时,当它说 timerLabel 时,我无法辨别这是否意味着键入“timerLabel”或者“timerLabel”是否是 my MZTimerLabel 的实例。

看起来协议(protocol)告诉我调用 MZTimerLabel 然后告诉它我的 View Controller 中的哪个实例要监听(我的实例称为 brewingTimer,但是我无法正确使用 Swift 语法。也许我应该在我的 ViewDidLoad() 中声明 brewingTimer.delegate = self

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

我的 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 方法的示例会非常有帮助。

最佳答案

你的委托(delegate)函数变得很快

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 中实现此操作。同时遵守协议(protocol)。 这里 timerLabelMZTimerLabel

的实例

同时导入你的协议(protocol)到Swift Bridging Header

关于syntax - 如何在 Swift 中重写 Objective C 委托(delegate)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25108919/

相关文章:

Swift 3 名称(大写与否)?

javascript - 为什么假的不会变成真的?

ios - 如何调整图像大小以适应包含的 ImageView

swift - runTransactionBlock 导致主线程延迟

css - CSS block 中的未闭合引号

python - 在 Python 中,%25s、%28s、%15s、%3s 等是什么意思?

objective-c - Swift IOS 中的异或加密

swift - 如何移动 SKNode?

c - 为什么 `&` 用于 C 中的二进制与和地址?

ios - 修复仅纵向模式或横向的应用程序