Detecting iOS UIDevice orientation

后端 未结 8 919
一生所求
一生所求 2020-11-28 03:29

I need to detect when the device is in portrait orientation so that I can fire off a special animation. But I do not want my view to autorotate.

How do I override a

8条回答
  •  一向
    一向 (楼主)
    2020-11-28 04:09

    1) Swift version of David's answer 2) In case you still want to detect orientation when there's no orientation change (Swift vesion of Moe's answer to How Do I detect the orientation of the device on iOS?)

        // Initial device orientation
        let orientation: UIInterfaceOrientation = UIApplication.sharedApplication().statusBarOrientation
        if(orientation == UIInterfaceOrientation.Unknown){
            // code for Unknown
        }
        else if(orientation == UIInterfaceOrientation.Portrait){
            // code for Portrait
        }
        else if(orientation == UIInterfaceOrientation.PortraitUpsideDown){
            // code for Portrait
        }
        else if(orientation == UIInterfaceOrientation.LandscapeRight){
            // code for Landscape        
        }
        else if(orientation == UIInterfaceOrientation.LandscapeLeft){
            // ode for Landscape
        }
    
        // To detect device orientation change
        UIDevice.currentDevice().beginGeneratingDeviceOrientationNotifications()
        NSNotificationCenter.defaultCenter().addObserver(
            self,
            selector: "orientationChanged:",
            name: UIDeviceOrientationDidChangeNotification,
            object: UIDevice.currentDevice())
    

    orientationChanged function

    func orientationChanged(note: NSNotification)
    {
        let device: UIDevice = note.object as! UIDevice
        switch(device.orientation)
        {
            case UIDeviceOrientation.Portrait:
            // code for Portrait
            break
            case UIDeviceOrientation.PortraitUpsideDown:
            // code for Portrait
            break
            case UIDeviceOrientation.LandscapeLeft:
            // code for Landscape
            break
            case UIDeviceOrientation.LandscapeRight:
            // code for Landscape
            break
            case UIDeviceOrientation.Unknown:
            // code for Unknown
            break
            default:
            break
        }
    }
    

提交回复
热议问题