The supportedInterfaceOrientations method doesn't override any method from its superclass

后端 未结 1 940
陌清茗
陌清茗 2020-11-30 06:08

In a UIViewController, this code:

public override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    if let mainController = self.m         


        
相关标签:
1条回答
  • 2020-11-30 06:29

    Like this:

    override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
    

    ...and the rest as you have it.

    The general pattern

    A lot of Cocoa methods are properties now, so you implement them as override computed variables. So the pattern for moving from seed 3 (or earlier) to seed 4 is:

    • Change func to var

    • Delete ()

    • Change -> to :

    This works because a computed variable has a getter function, so the function you were implementing before simply turns into the getter function. And these are read-only properties, so you won't need a setter.

    Similarly affected methods are preferredStatusBarStyle, prefersStatusBarHidden, shouldAutorotate, preferredInterfaceOrientationForPresentation, and many others. Look for UIKIT_DEFINE_AS_PROPERTIES in the Objective-C header.

    Implications

    In the longer term, there are other changes you can make. For example, you can add a setter (dividing your implementation into get and set functions), and thus you can turn your implementation into a facade for a stored property. For example:

    private var _orientations = UIInterfaceOrientationMask.portrait
    override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
        get { return self._orientations }
        set { self._orientations = newValue }
    }
    

    So now your code has a way to set this value. If you were returning different values at different times, this could make things a lot cleaner.

    Further technical notes

    Interestingly, this change has no direct effect on existing Objective-C code, because in Objective-C, the new property declaration, @property(nonatomic, readonly) UIInterfaceOrientationMask supportedInterfaceOrientations;, is satisfied by the same method as before:

    - (UIInterfaceOrientationMask)supportedInterfaceOrientations {
        return UIInterfaceOrientationMaskPortrait;
    }
    

    The reason is that in Objective-C, a @property(readonly) is merely a promise that a corresponding getter method exists, and that's exactly what this method is. But in Swift, the way to write an Objective-C property's getter method is through a property, that is, through an instance variable. So only Swift code is affected by the change: you have to rewrite your methods as properties.

    0 讨论(0)
提交回复
热议问题