您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS UIActionSheet 使用要點與常見誤區

編輯:iOS 開發綜合

研究 UIActionSheet 時,我直接把程式碼貼進 viewDidLoad 執行,結果怎麼跑都有問題,甚至懷疑是 Xcode 壞了。後來才想到,平常使用時都是放在某個按鈕的點擊方法裡,於是產生一個想法:UIActionSheet 必須搭配使用者動作才會生效。

查了官方文件,確實有這麼一句話印證了這個觀點:Action sheets display a set of buttons representing several alternative choices to complete a task initiated by the user. 也就是說,它本質上是用來回應使用者所發起的操作,而不是拿來在主動畫流程中自動彈出。

官方文件:
https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/UIKitUICatalog/UIActionSheet.html

基本程式碼

@interface sheetviewViewController : UIViewController <UIActionSheetDelegate>
@end

UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"first ActionSheet"
                                                        delegate:self
                                               cancelButtonTitle:@"取消"
                                          destructiveButtonTitle:@"刪除"
                                                otherButtonTitles:@"保持", nil];

actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
[actionSheet showInView:self.view];

委派回呼

#pragma mark --- 實作 UIActionSheetDelegate 協議
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        [self showAlert:@"確定"];
    } else if (buttonIndex == 1) {
        [self showAlert:@"第一項"];
    } else if (buttonIndex == 2) {
        [self showAlert:@"第二項"];
    } else if (buttonIndex == 3) {
        [self showAlert:@"取消"];
    }

    NSString *buttonTitle = [actionSheet buttonTitleAtIndex:buttonIndex];
    NSLog(@"buttonTitle = %@", buttonTitle);
}

參數說明

初始化方法中有兩個參數是系統預留的固定項目:cancelButtonTitle 是取消按鈕,destructiveButtonTitle 是破壞性操作按鈕。otherButtonTitles 則是自行定義的項目,可以帶多個,但參數列表最後必須以 nil 結束,否則會讀到記憶體中的垃圾值。

[actionSheet showInView:self.view] 表示在目前 view 上顯示 action sheet,當然也有 showFromTabBar:、showFromToolbar: 等其他呈現方式可選。

回呼中的 buttonIndex 就是按鈕的索引,依加入順序遞增。

破壞性按鈕

那顆紅色的按鈕,就是所谓的破壞性按鈕,用來對某個不可逆的操作起到警示作用,例如永久刪除一則訊息或一張圖片。指定之後它會以紅色高亮顯示:

actionSheet.destructiveButtonIndex = 1;

三種樣式

與導覽列類似,action sheet 也提供三種風格:

UIActionSheetStyleDefault          // 預設風格:灰色背景配白色文字
UIActionSheetStyleBlackTranslucent // 半透明黑色背景,白色文字
UIActionSheetStyleBlackOpaque      // 純黑背景,白色文字

// 用法
actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;

一個重要提醒

UIActionSheet 在 iOS 8 之後已被標記為廢棄,官方建議改用 UIAlertController 並指定 UIAlertControllerStyleActionSheet。新專案請直接採用新 API,除了避免警告,也能拿到更好的深色模式與動態字型支援。

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