简体   繁体   English

检测UIView子类内的自动旋转

[英]Detect autorotation inside UIView subclass

I'm creating a subclass of UIView that needs to relayout its subviews when the orientation changes. 我正在创建一个UIView的子类,当方向改变时需要重新布局其子视图。

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 它需要能够“插入任何地方”而无需任何额外的代码,所以我宁愿不依赖UIViewController方法来检测自转

Is there anyway for the UIView to know when the orientation has changed? 无论如何,UIView知道方向何时发生了变化?

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

I found that for me this worked better than the UIDeviceOrientationDidChangeNotification: 我发现对我来说这比UIDeviceOrientationDidChangeNotification更好用:

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

I didn't even need to add the first line with beginGeneratingDeviceOrientationNotifications. 我甚至不需要在beginGeneratingDeviceOrientationNotifications中添加第一行。

In Swift, it will be done like this: 在Swift中,它将像这样完成:

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

@objc private func orientationChange(inNotification:Notification) -> Void {
      // handle notification
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM