Need help setting up an interface where rotation i

2019-02-26 05:25发布

问题:

I'm working with Xcode 7 and Swift 2. I am working on an interface with a camera preview layer and controls that display in a manner similar to the native iOS camera app. The controls all stay in place as you turn the device, but the icons "pivot" in place to orient properly for the device orientation. (I hope I explained that in a way that makes sense. If not, open the native camera app on your iPhone and turn the device around a few times to see what I'm talking about.)

I have the basic interface working already by fixing the overall interface orientation using:

override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
        return UIInterfaceOrientationMask.LandscapeRight
}

Then I use transform to rotate each button for the device orientation.

The problem is: I need to be able to present alert messages (UIAlertController) and a sharing interface (UIActivityViewController) in this same interface. How do I get those items to rotate to the correct orientation while still keeping the rest of the interface static?

As I see it, there are two possible approaches here -- I just don't know how to make either one work:

  1. Set the interface to auto rotate and support all orientations, but disable auto-rotation for the views that I need to keep locked in place.

  2. Set the interface to only allow .landscapeLeft (which is currently how it's set up) and find a way to rotate the alert messages and sharing dialog box.

回答1:

Got it working. I needed to access presentedViewController.view to rotate the alert and share views.

//used to periodically trigger a check of orientation
var updateTimer: NSTimer?

//Checks if the device has rotated and, if so, rotates the controls. Also prompts the user that portrait orientation is bad.
func checkOrientation(timer: NSTimer) {
    //Array of the views that need to be rotated as the device rotates
    var viewsToRotate = [oneView, anotherView]

    //This adds the alert or sharing view to the list, if there is one
    if let presentedVC = presentedViewController?.view {
        viewsToRotate.append(presentedVC)
    }

    //Rotate all of the views identified above
    for viewToRotate in viewsToRotate {
        switch UIDevice.currentDevice().orientation {
        case UIDeviceOrientation.Portrait:
            viewToRotate.transform = CGAffineTransformMakeRotation(CGFloat(-M_PI_2))
        case UIDeviceOrientation.PortraitUpsideDown:
            viewToRotate.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_2))
        case UIDeviceOrientation.LandscapeRight:
            viewToRotate.transform = CGAffineTransformMakeRotation(CGFloat(2 * M_PI_2))
        default:
            viewToRotate.transform = CGAffineTransformMakeRotation(CGFloat(0))
        }
    }
}