Pregunta

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?

¿Fue útil?

Solución

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];

Otros consejos

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.

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
 }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top