简体   繁体   中英

Force ipad orientation for one view

I'm trying to force the orientation for one view in my ipad app but I can't keep it persistent.

For example, I'm in portrait in my collection view, I select an image (which is landscape). I check it's width and it's height in the viewWillAppear of my viewPhoto in order to set the device to landscape. The "device" rotate, well. When I rotate it manually after to portrait, I want it to stay in landscape, but it doesn't.

Here's my code :

override func viewWillAppear(animated: Bool) {
    // Remove hairline on toolbar
    mytoolBar.clipsToBounds = true

    // Load image from svg
    let img = getImageFromBase64(arrayBase64Images[index])
    imgView.image = img

    var value: Int
    if ( img.size.width > img.size.height ) { // turn device to landscape
        value = UIInterfaceOrientation.LandscapeRight.rawValue
    }
    else { // turn device to portrait
        value = UIInterfaceOrientation.Portrait.rawValue
    }
    UIDevice.currentDevice().setValue(value, forKey: "orientation")

}

I tinkered this solution, not exactly what I wanted but it does the job :

override func viewWillAppear(animated: Bool) {
    // Remove hairline on toolbar
    mytoolBar.clipsToBounds = true

    // Load image from svg
    let img = getImageFromBase64(arrayBase64Images[index])
    imgView.image = img

    var value: Int

    if ( img.size.width > img.size.height ) { // turn device to landscape
        if( !UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation) )
        {
            value = UIInterfaceOrientation.LandscapeRight.rawValue
            UIDevice.currentDevice().setValue(value, forKey: "orientation")
        }
        landscape = true
    }
    else { // turn device to portrait
        if( !UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation) )
        {
            value = UIInterfaceOrientation.Portrait.rawValue
            UIDevice.currentDevice().setValue(value, forKey: "orientation")
        }
        landscape = false
    }

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "rotated", name: UIDeviceOrientationDidChangeNotification, object: nil)

}

func rotated()
{
    if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation))
    {
        if ( !landscape ) {
            let value = UIInterfaceOrientation.Portrait.rawValue
            UIDevice.currentDevice().setValue(value, forKey: "orientation")
        }
    }

    if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation))
    {
        if ( landscape ) {
            let value = UIInterfaceOrientation.LandscapeRight.rawValue
            UIDevice.currentDevice().setValue(value, forKey: "orientation")
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM