Detect autorotation inside UIView subclass
Asked Answered
H

3

5

I'm creating a subclass of UIView that needs to relayout its subviews when the orientation changes.

it needs to be able to "plug in anywhere" without any extra code so I'd rather not rely on the UIViewController methods to detect the autorotation

Is there anyway for the UIView to know when the orientation has changed?

Hyaline answered 26/8, 2013 at 7:32 Comment(0)
C
9

How about a notification like this to detect the orientation change??

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:nil]; 

But, before that you need to register for generating notifications like this.

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
Coles answered 26/8, 2013 at 10:26 Comment(0)
O
0

I found that for me this worked better than the UIDeviceOrientationDidChangeNotification:

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("layoutControls"), name: UIApplicationDidChangeStatusBarOrientationNotification, object: nil)

I didn't even need to add the first line with beginGeneratingDeviceOrientationNotifications.

Oneal answered 23/11, 2015 at 10:44 Comment(0)
D
0

In Swift, it will be done like this:

NotificationCenter.default.addObserver(self, selector: #selector(orientationChange(inNotification:)), name: NSNotification.Name.UIApplicationDidChangeStatusBarOrientation, object: nil)

@objc private func orientationChange(inNotification:Notification) -> Void {
      // handle notification
 }
Darelldarelle answered 8/12, 2018 at 17:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.