ios - 子类中未调用 Swift 3 ObjC 可选协议(protocol)方法

标签 ios swift cocoa-touch swift3 ios10

我有以下类层次结构:

class ScrollableViewController: UIViewController, UITableViewDelegate { // ... }

它实现了一个 UITableViewDelegate 协议(protocol)方法,例如tableView:willDisplayCellAt:

在我继承自 ScrollableViewController 的类 SpecificScrollableViewController 中,不再调用新的可选协议(protocol)方法,例如tableView(_:heightForRowAt:)

最佳答案

tl;dr 你需要在函数声明前加上它的 Objective-C 声明,例如

@objc(tableView:heightForRowAtIndexPath:)
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  // return stuff
}

由于 Swift 3 Migration Guide,我被告知这是一个解决方案其中指出:

If you implement an optional Objective-C protocol requirement in a subclass of a class that declares conformance, you’ll see a warning, “Instance method ‘…’ nearly matches optional requirement ‘…’ of protocol ‘…’”

• Workaround: Add an @objc(objectiveC:name:) attribute before the implementation of the optional requirement with the original Objective-C selector inside.

我相当确定这是一个错误:当协议(protocol)方法位于子类中时,允许检查选择器功能的运行时动态似乎没有在 Grand Swift 重命名中正确桥接。使用 Objective-C 名称作为函数声明的前缀可以正确地将 Swift 桥接到 Objective-C,并允许在 Objective-C 中使用 canPerformAction:withSender: 查询 Swift 3 重命名的方法

关于ios - 子类中未调用 Swift 3 ObjC 可选协议(protocol)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39416385/

相关文章:

swift - 如何使用 Swift 协议(protocol)扩展来创建可以修改私有(private)属性的共享代码?

ios - 真的很奇怪的 drawRect 行为??

iphone - 动画期间 UIView 缩放

ios - 什么时候在 NSManagedObject 上调用 initWithCoder?

ios - 打包 Apache Cordova App 需要 Mac 吗?

iOS 9.2.1 应用程序在启动时崩溃

swift - 何时使用 IBAction 与 UITapGestureRecognizer?

iphone - 当通过 UIWebView 播放电影,然后通过 Airplay 输出到 AppleTV 时,关闭 iPhone 屏幕会停止播放。为什么?

ios - 我在动画结束后是否太早释放该对象?

ios - ABAddressBookRequestAccessWithCompletion 的最佳实践