簡體   English   中英

檢測UIView子類內的自動旋轉

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM