您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 技巧大全

用 UIDevice 偵測裝置朝向

編輯:iOS 技巧大全

需要依裝置方向切換介面時,UIDevice 是最直接的工具。它透過通知中心散播朝向變化,你只要註冊觀察者即可。

開始監聽

- (void)viewDidLoad {
    [super viewDidLoad];

    // 啟用朝向通知,UIDevice 才會開始向通知中心發送資訊
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

    // 註冊觀察者
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(orientationChanged:)
                                                 name:UIDeviceOrientationDidChangeNotification
                                               object:nil];
}

處理通知

-(void)orientationChanged:(NSNotification *)notification {
    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation;

    switch (orientation) {
        case UIDeviceOrientationFaceUp:
            NSLog(@"設備正面朝上");
            break;
        case UIDeviceOrientationFaceDown:
            NSLog(@"設備正面朝下");
            break;
        case UIDeviceOrientationPortrait:
            NSLog(@"設備處於正常朝向,主螢幕按鈕在下方");
            break;
        case UIDeviceOrientationPortraitUpsideDown:
            NSLog(@"設備縱向倒置,主螢幕按鈕在上方");
            break;
        case UIDeviceOrientationLandscapeLeft:
            NSLog(@"設備側立,左邊朝下");
            break;
        case UIDeviceOrientationLandscapeRight:
            NSLog(@"設備側立,右邊朝下");
            break;
        default:
            break;
    }
}

兩點提醒

第一,beginGeneratingDeviceOrientationNotifications 啟動的是硬體感測,會增加耗電,離開頁面時記得呼叫 endGeneratingDeviceOrientationNotifications 並移除觀察者,否則通知會持續散播,也容易在 dealloc 後造成 crash。

第二,UIDeviceOrientation 與 UIInterfaceOrientation 是兩套不同的東西。前者描述裝置在空間中的物理姿態(可能正面朝上、完全躺平),後者描述介面的方向。想做「使用者把裝置平放桌上」這類判斷才需要 UIDevice;單純的畫面旋轉應該用 Size Class 或 orientation 相關的 view 方法處理。

順帶一提:取得系統版本

UIDevice *device = [UIDevice currentDevice];
NSLog(@"%@", device.systemVersion);

UIDevice 同時也提供 model、name、systemName 等資訊,是收集裝置環境資料的 handy 入口。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved