【发布时间】:2016-06-08 15:32:58
【问题描述】:
我正在开发具有 Obj C 代码和 Swift 的 iOS 应用程序。我正在将现有的 Objective C 类别迁移到 swift 代码。但是当我在 swift 扩展中覆盖现有方法时,它不会编译。 Swift 扩展适用于新方法,但不适用于覆盖现有方法。
代码:
extension UIViewController {
public override func shouldAutorotate() -> Bool {
return false
}
public override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.Portrait
}
}
错误:
Method 'shouldAutorotate()' with Objective-C selector 'shouldAutorotate' conflicts with previous declaration with the same Objective-C selector
Method does not override any method from its superclass
Method 'supportedInterfaceOrientations()' with Objective-C selector 'supportedInterfaceOrientations' conflicts with previous declaration with the same Objective-C selector
在这里,我错过了什么吗?
我正在使用Xcode 7.3.1 和Swift 2.x
编辑:
从下面的答案中,我知道我们不能像在 Objective C 类别中那样在 Swift 扩展中更改现有类方法在运行时的行为。在这里,我应该创建一个将覆盖方法的基类,并且我应该使用我所有的 ViewControllers 作为新基类中的子类作为父类。
但就我而言,我想更改所有“shouldAutorotate”方法的行为,包括第 3 方框架 UIViewController。在上述情况下,我不能强制所有第三方框架 UIviewControllers 成为我的基类的子类。在Objective C中我可以做到这一点。
【问题讨论】:
标签: ios objective-c swift swift2