-1

I am writing a graphing app - Landscape positions the content within the portrait's coordinate system. What is the simplest way for my viewController to detect an orientation change?

edit I am aware there is a similar question from sept 2014, but the solution appears code specific - could someone clarify what the simplest way to detect rotation might be? (code explanation good too)

I tried the implementation but keep getting a "expected declaration" error on NSNotificationCenter

(and for clarity's sake, here's the referenced solution:)

In AppDelegate.swift inside the "didFinishLaunchingWithOptions":

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

in the AppDelegate class:

func rotated()
{
    if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation))
    {            
        println("landscape")
    }
    if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation))
    {
        println("Portrait")
    }
}
John
  • 465
  • 6
  • 14
  • Duplicate: http://stackoverflow.com/questions/25666269/ios8-swift-how-to-detect-orientation-change – FabKremer Jul 19 '15 at 23:23
  • I had checked that thread before asking my question - I don't have a appdelegate.swift file and am not clear as to how to go about it. furthermore, I am asking for the simplest way... I was hoping there was something more straightforward. – John Jul 19 '15 at 23:45
  • You can put that code wherever you want. It doesn't need to be in the AppDelegate. – FabKremer Jul 19 '15 at 23:48

2 Answers2

0

Here's the simplest way I found to react to a rotation, which should be an easy implementation for most - the overridden function gets called "any time a view's frame changed and its subviews were thus re-layed out" (credit: Stanford CS193p slides)

in the viewController (of the view that will rotate):

override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()
    // code to handle rotation details
}
John
  • 465
  • 6
  • 14
  • you should not put anything in viewDidLayoutSubviews as you don't know when it is called or how many times it is called. – George Asda Nov 03 '16 at 19:55
0

There is a problem with this method. If you have many subviews added on your main view this function will be called many times.

I think the best way is:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    // Your Processing
}

Moreover, you have parameters to help you in your handling.

Peter Hall
  • 53,120
  • 14
  • 139
  • 204
Guigs
  • 1
  • 1