在UIViewController中,这段代码:
public override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if let mainController = self.mainViewController{
return mainController.supportedInterfaceOrientations
}
return UIInterfaceOrientationMask.all
}
Run Code Online (Sandbox Code Playgroud)
给出了错误 Method doesn't override any method from its superclass
我使用的是Xcode 8 beta 4,iOS部署目标是9.0,并且Use Legacy Swift Language Version
设置为NoBuild Settings
我怎么能将上面的代码转换为Swift 3?
mat*_*att 77
像这样:
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
Run Code Online (Sandbox Code Playgroud)
......以及你拥有的其余部分.
现在很多Cocoa方法都是属性,因此您可以将它们实现为覆盖计算变量.因此从种子3(或更早)移动到种子4的模式是:
更改func
到var
删除 ()
更改->
到:
这是因为计算变量有一个getter函数,所以你之前实现的函数只是变成了getter函数.这些是只读属性,因此您不需要setter.
同样受影响的方法是preferredStatusBarStyle
,prefersStatusBarHidden
,shouldAutorotate
,preferredInterfaceOrientationForPresentation
,和其他许多人.UIKIT_DEFINE_AS_PROPERTIES
在Objective-C标题中查找.
从长远来看,您可以进行其他更改.例如,您可以添加一个setter(将您的实现划分为get
和set
函数),这样您就可以将您的实现转换为存储属性的外观.例如:
private var _orientations = UIInterfaceOrientationMask.portrait
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
get { return self._orientations }
set { self._orientations = newValue }
}
Run Code Online (Sandbox Code Playgroud)
所以现在你的代码有办法设置这个值.如果你在不同的时间返回不同的值,这可以使事情变得更加清晰.
有趣的是,此更改对现有的Objective-C代码没有直接影响,因为在Objective-C中,新属性声明@property(nonatomic, readonly) UIInterfaceOrientationMask supportedInterfaceOrientations;
通过与以前相同的方法得到满足:
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskPortrait;
}
Run Code Online (Sandbox Code Playgroud)
原因是在Objective-C中,a @property(readonly)
仅仅是一个相应的getter方法存在的承诺,而这正是这个方法的本质.但是在Swift中,编写Objective-C属性的getter方法的方法是通过一个属性,即通过一个实例变量.因此,只有Swift代码会受到更改的影响:您必须将方法重写为属性.
归档时间: |
|
查看次数: |
17337 次 |
最近记录: |