![](/img/trans.png)
[英]UIView Subclass: Detect the size of a UIView set up in Interface Builder which uses said UIView subclass as a custom class
[英]Detect autorotation inside UIView subclass
我正在创建一个UIView的子类,当方向改变时需要重新布局其子视图。
它需要能够“插入任何地方”而无需任何额外的代码,所以我宁愿不依赖UIViewController方法来检测自转
无论如何,UIView知道方向何时发生了变化?
这样的通知如何检测方向变化?
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:nil];
但是,在此之前,您需要注册以生成这样的通知。
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
我发现对我来说这比UIDeviceOrientationDidChangeNotification更好用:
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("layoutControls"), name: UIApplicationDidChangeStatusBarOrientationNotification, object: nil)
我甚至不需要在beginGeneratingDeviceOrientationNotifications中添加第一行。
在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.