I'm porting my iPad app to iOS8 and Swift.
In portrait, i use a root UIViewController and when the de device is rotated to landscape, I segue to another UIViewController. I've come up with 2 solutions, one based on UIDevice notifications and the other on willRotateToInterfaceRotation
. I alway try to stay away from the Observer pattern, it's just a habit of me.
The Observer works fine, but the override in both UIViewController of func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) looks cleaner to my eyes ;)
But now in iOS8 that function is deprecated and I should use
func viewWillTransitionToSize(_ size: CGSize,
withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator)
But I don't have any idea how I can work with that to get the same result.
This is the rootViewController
:
override func willRotateToInterfaceOrientation(
toInterfaceOrientation: UIInterfaceOrientation,
duration: NSTimeInterval) {
if (toInterfaceOrientation == UIInterfaceOrientation.LandscapeLeft ||
toInterfaceOrientation == UIInterfaceOrientation.LandscapeRight) {
self.performSegueWithIdentifier("toLandscape", sender: self)
}
}
and the UIViewControllerLanscape
:
override func willRotateToInterfaceOrientation(
toInterfaceOrientation: UIInterfaceOrientation,
duration: NSTimeInterval) {
if (toInterfaceOrientation == UIInterfaceOrientation.Portrait ||
toInterfaceOrientation == UIInterfaceOrientation.PortraitUpsideDown) {
self.presentingViewController?.dismissViewControllerAnimated(true,
completion: nil)
}
}
I don't like to use deprecated functions, so I'm in doubt what to do...go for the observer or what??
This is the code I use when (only) the root UIViewController is an observer of the UIDeviceOrientationDidChangeNotification:
override func awakeFromNib() {
let dev = UIDevice.currentDevice()
dev.beginGeneratingDeviceOrientationNotifications()
let nc = NSNotificationCenter.defaultCenter()
nc.addObserver(self, selector: "orientationChanged:", name: UIDeviceOrientationDidChangeNotification, object: dev)
}
func orientationChanged(note: NSNotification) -> () {
if let uidevice: UIDevice = note.object? as? UIDevice {
switch uidevice.orientation {
case .LandscapeLeft, .LandscapeRight:
self.performSegueWithIdentifier("toLandscape", sender: self)
default:
self.dismissViewControllerAnimated(true, completion: nil)
}
}
}
I really like your ideas on how to make a solution for these deprecated functions. It's a total mystery to me....or maybe the Observer is the better solution now. Please share your ideas.
Regards,
jr00n