像这样:
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
...剩下的就按你所拥有的那样。
一般模式
许多 Cocoa 方法现在都是属性,因此您可以将它们实现为覆盖计算变量。因此,从种子 3(或更早)移动到种子 4 的模式是:
Change func
to var
Delete ()
Change ->
to :
这是可行的,因为计算变量有一个 getter 函数,因此您之前实现的函数只是变成了 getter 函数。这些是只读属性,因此您不需要设置器。
同样受影响的方法有preferredStatusBarStyle
, prefersStatusBarHidden
, shouldAutorotate
, preferredInterfaceOrientationForPresentation
,以及许多其他人。寻找UIKIT_DEFINE_AS_PROPERTIES
在 Objective-C 头文件中。
影响
从长远来看,您还可以做出其他改变。例如,你can添加一个设置器(将您的实现分为get
and set
函数),因此您可以将您的实现转变为存储属性的外观。例如:
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 方法的方法是通过property,即通过实例变量。因此,只有 Swift 代码会受到更改的影响:您必须将方法重写为属性。