supportedInterfaceOrientations方法不会覆盖其超类中的任何方法
在UIViewController中,这个代码:
public override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if let mainController = self.mainViewController{ return mainController.supportedInterfaceOrientations } return UIInterfaceOrientationMask.all }
给出的错误Method doesn't override any method from its superclass
我正在使用Xcode 8 beta 4,iOS部署目标是9.0,并且在Build Settings
中将“ Use Legacy Swift Language Version
设置为“否Build Settings
我怎么能把上面的代码转换成Swift 3?
喜欢这个:
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
剩下的就像你一样
一般的模式
现在很多Cocoa方法都是属性,所以你把它们作为override计算variables来实现。 所以从种子3(或更早)移动到种子4的模式是:
-
将
func
更改为var
-
删除
()
-
更改
->
到:
这是可行的,因为一个计算variables有一个getter函数,所以你之前执行的函数只是变成了getter函数。 而这些是只读属性,所以你不需要setter。
同样受影响的方法是preferredStatusBarStyle
, prefersStatusBarHidden
, prefersStatusBarHidden
, preferredInterfaceOrientationForPresentation
和许多其他。 在Objective-C头文件中查找UIKIT_DEFINE_AS_PROPERTIES
。
启示
从长远来看,还有其他的变化。 例如,您可以添加一个setter(将您的实现划分为get
和set
函数),因此您可以将实现转换为存储属性的facade。 例如:
private var _orientations = UIInterfaceOrientationMask.portrait override var supportedInterfaceOrientations : UIInterfaceOrientationMask { get { return self._orientations } set { self._orientations = newValue } }
所以现在你的代码有一个方法来设置这个值。 如果你在不同的时间返回不同的值,这可能使事情变得更加清洁。
更多的技术说明
有趣的是,这个改变对现有的Objective-C代码没有直接的影响,因为在Objective-C中,新的属性声明@property(nonatomic, readonly) UIInterfaceOrientationMask supportedInterfaceOrientations;
,用与以前相同的方法来满足:
- (UIInterfaceOrientationMask)supportedInterfaceOrientations { return UIInterfaceOrientationMaskPortrait; }
原因是在Objective-C中, @property(readonly)
仅仅是一个相应的getter方法存在的承诺,而这正是这个方法的意义所在。 但在Swift中,编写Objective-C属性的getter方法的方法是通过一个属性 ,也就是通过一个实例variables。 所以只有Swift代码会受到更改的影响:您必须将您的方法重写为属性。