为一个视图强制 ipad 方向

Force ipad orientation for one view

我试图在我的 ipad 应用程序中强制显示一个视图的方向,但我无法保持它的持久性。

例如,我在 collection 视图中是纵向的,我 select 图像(横向)。我在我的 viewPhoto 的 viewWillAppear 中检查它的宽度和高度,以便将设备设置为横向。 "device" 旋转,嗯。当我手动旋转它到纵向后,我希望它保持横向,但它没有。

这是我的代码:

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")

}

我修改了这个解决方案,虽然不是我想要的,但它确实起作用了:

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")
        }
    }
}