![](/img/trans.png)
[英]Detect rotation in UIInputViewController subclass. Keyboard extension
[英]Catch rotation event into UIInputViewController
我正在開發自定義鍵盤,並且試圖捕獲設備旋轉事件。
我已經嘗試過了:
override func viewDidLayoutSubviews() {
print("Foo")
}
和
override func viewWillLayoutSubviews() {
print("🐳🐳🐳🐳🐳🐳🐳🐳🐳🐳🐳🐳 Bar")
}
和
override func didRotateFromInterfaceOrientation(sender : UIInterfaceOrientation){
print("🐳🐳🐳🐳");
}
和
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
print("Bar")
}
和
override func updateViewConstraints() {
super.updateViewConstraints()
print("🐳🐳🐳🐳🐳🐳🐳🐳🐳🐳🐳🐳 Foo")
}
但這不起作用。
iPad Air 2模擬器-iOS9
任何想法 ?
現在不推薦使用大多數與旋轉有關的方法。 蘋果正朝着尺寸和特征更改通知的方向發展,而不是直接面向設備方向的更改通知。
同樣,在具有完全訪問權限和beginGeneratingDeviceOrientationNotifications的鍵盤擴展中,UIDevice.currentDevice()。orientation始終返回Unknown。
正確的方法(以及替代文檔中不推薦使用的方法的方法)是
- viewWillTransitionToSize:withTransitionCoordinator:
奇怪的是它對您不起作用。 我只是在iPad Air 2 iOS9 Simulator的UIInputViewController中嘗試過,它的工作原理是:
2015-10-13 12:28:15.347 [Info] [KeyboardViewController.swift:60] viewWillTransitionToSize( :withTransitionCoordinator :)>旋轉至大小(1024.0,313.0)2015-10-13 12:28:20.512 [Info] [KeyboardViewController .swift:60] viewWillTransitionToSize( :withTransitionCoordinator :)>旋轉至大小(768.0,313.0)
您是否在調試正確的目標? 要查看擴展中的控制台消息,必須將其設置為運行目標:
請注意,還有
- willTransitionToTraitCollection:withTransitionCoordinator:
但這不適用於iPad,因為iPad始終對風景和人像都是“常規”,“常規”。
並非所有的視圖控制器都將接收過渡事件。 我認為這取決於您的視圖控制器是否在UINavigationController或UITabBarController之類的容器控制器內部,以及它們是否將更改傳遞給其子控制器。
接收方向更改的保證方法是注冊UIDevice方向更改通知。 有關通知事件的列表,請參見https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIDevice_Class/#//apple_ref/c/data/UIDeviceOrientationDidChangeNotification 。
這是您在ObjC中要做的事情。 應該足夠容易地轉換為Swift。
在您的應用程序委托中,使用以下方法激活方向更改:
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
在視圖控制器中,您希望通知添加方法來處理通知,添加和刪除觀察通知。
// Method to be called when orientation notification is changed.
- (void)orientationDidChange:(NSNotification *)notification {
// Add your code to deal with the orientation.
// You can get the current orientation for UIDevice as follows:
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
}
// Adds observation of orientation change
-(void)addObserver
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(orientationDidChange:)
name:@"UIDeviceOrientationDidChangeNotification"
object:nil];
}
// Removes observation of orientation change
-(void)removeObserver
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
在適當的位置添加對addObserver
和removeObserver
調用。 例如, viewDidAppear
和viewDidDisappear
。
看來這在我的iOS 9和iPad Air 2項目中適用。
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
print("hi")
}
看起來您嘗試過,但是卻沒有效果...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.