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

iOS 自訂彈出視窗的實作範例

編輯:iOS 7 技巧

要在畫面上彈出一個對話框,iOS 提供了好幾種途徑。以下示範一種做法:把對話窗本身做成一個獨立的 view controller,再以 modal 方式覆蓋上去。這樣做的好處是內容與樣式完全自訂,不受 UIAlertController 版型限制。

核心概念:這個對話窗其實就是一個普通的 ModalViewController。

// 判斷系統版本
#define iOSVersionGreaterThanOrEqualTo(v) \
    ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

// 按鈕觸發事件
- (void)buttonPressed:(id)sender
{
    ModalViewController *modalVC = [[ModalViewController alloc] init];
    modalVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;

    if (iOSVersionGreaterThanOrEqualTo(@"8.0")) {
        modalVC.providesPresentationContextTransitionStyle = YES;
        modalVC.definesPresentationContext = YES;
        modalVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        [self presentViewController:modalVC animated:YES completion:nil];
    }
    else {
        self.view.window.rootViewController.modalPresentationStyle = UIModalPresentationCurrentContext;
        [self presentViewController:modalVC animated:NO completion:nil];
        self.view.window.rootViewController.modalPresentationStyle = UIModalPresentationFullScreen;
    }
}

為什麼要分版本處理

差別在於 UIModalPresentationOverCurrentContext 這個呈現樣式。它讓被呈現的 view controller 背景透明,能透出底下的內容——這正是「彈窗」而非「換頁」的視覺效果。這個樣式是 iOS 8 才引入的,因此舊系統只能退回 UIModalPresentationCurrentContext 的舊寫法。

搭配 UIModalTransitionStyleCrossDissolve(淡入淡出)而不是預設的由下往上推,視覺上才像一個浮在畫面上的對話框。

幾個可以更好的地方

如果 App 的最低支援版本已經是 iOS 8 以上,上面整段版本判斷都可以刪掉,程式碼會乾淨很多。另外,若只是想顯示簡單的提示與按鈕,直接用 UIAlertController 的 alertControllerWithStyle: 會更省事,並自動符合系統的無障礙與外觀設定;自訂 view controller 的代價是你必須自己處理 VoiceOver 標記、動態字型與深色模式。若要顯示的是「一段操作流程」而非單純提示,自訂 modal 才是對的選擇。

最後提醒:以自訂 view controller 充當彈窗時,記得在背景加一個半透明遮罩並攔截點擊,否則使用者可能誤觸底下仍在互動的畫面。

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