子类中未调用 Swift 3 ObjC 可选协议方法 [英] Swift 3 ObjC Optional Protocol Method Not Called in Subclass

查看:29
本文介绍了子类中未调用 Swift 3 ObjC 可选协议方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类层次结构:

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

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

That implements one UITableViewDelegate protocol method, e.g. tableView:willDisplayCellAt:

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

In my class SpecificScrollableViewController, which inherits from ScrollableViewController, new optional protocol methods don't get called any more, e.g. tableView(_:heightForRowAt:)

推荐答案

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

tl;dr you need to prefix the function declaration with its Objective-C declaration, e.g.

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

感谢 Swift 3 迁移指南 说明:

如果您在声明一致性的类的子类中实现可选的 Objective-C 协议要求,您将看到警告,实例方法 '...' 几乎匹配协议 '...' 的可选要求 '...'"

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 ‘…’"

• 解决方法:在使用原始 Objective-C 选择器实现可选要求之前添加 @objc(objectiveC:name:) 属性.

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

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

I'm fairly certain this is a bug: it appears that the the runtime dynamism that allows checking for selector capability does not get properly bridged in the Grand Swift Renaming when the protocol method is in the subclass. Prefixing the function declaration with the Objective-C name properly bridges the Swift to Objective-C and allows Swift 3 renamed methods to be queried with canPerformAction:withSender: from within Objective-C

这篇关于子类中未调用 Swift 3 ObjC 可选协议方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆