【问题标题】:The supportedInterfaceOrientations method doesn't override any method from its superclasssupportedInterfaceOrientations 方法不会覆盖其超类中的任何方法
【发布时间】:2016-12-08 13:07:23
【问题描述】:

在 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 SettingsUse Legacy Swift Language Version设置为No

如何将上面的代码转换为 Swift 3?

【问题讨论】:

    标签: ios swift xcode


    【解决方案1】:

    像这样:

    override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
    

    ...剩下的就随你了。

    一般模式

    现在很多 Cocoa 方法都是属性,因此您可以将它们实现为覆盖计算变量。所以从种子 3(或更早)移动到种子 4 的模式是:

    • func更改为var

    • 删除()

    • ->更改为:

    这是因为计算变量有一个 getter 函数,所以你之前实现的函数只是变成了 getter 函数。而且这些是只读属性,因此您不需要 setter。

    受到类似影响的方法是preferredStatusBarStyleprefersStatusBarHiddenshouldAutorotatepreferredInterfaceOrientationForPresentation 等等。在 Objective-C 标头中查找 UIKIT_DEFINE_AS_PROPERTIES

    含义

    从长远来看,您还可以进行其他更改。例如,您可以添加一个setter(将您的实现分为getset 函数),因此您可以将您的实现变成存储属性的外观。例如:

    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 代码会受到更改的影响:您必须将方法重写为属性。

    【讨论】:

    • 你会经常这样做,所以现在就习惯吧。 :)
    • 我添加了将方法覆盖转换为属性覆盖的具体步骤!
    • 太棒了!只是等待接受您的回答所需的时间
    • 等等,还有更多!还解释了为什么这种变化真的很酷。
    • @Aetherynne 已经快一年了,我不知道。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-22
    相关资源
    最近更新 更多