Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

iOS 開發實作:UIActionSheet 的建立與選項事件回呼

UIActionSheet 是 iOS 上從底部彈出的選項清單,可以一次放多個項目,並為每一項處理點擊事件,常用於「拍攝/從相簿選取」這類操作分流。

準備工作

開啟 Xcode 4.3.2,建立一個 Single View Application,在 xib 上拖一個 button,用來觸發 sheet。

步驟一:宣告委派協議

在 .h 檔的 @interface 行尾加上 <UIActionSheetDelegate>。協議相當於 Java 的介面,宣告之後實作其中的方法即可。

@interface sheetviewViewController : UIViewController <UIActionSheetDelegate>
@end

步驟二、三:綁定按鈕與 Action

把 button 命名為 showSheetView,按住 Ctrl 拖曳到 .h 檔建立 Action 映射,事件類型選 Action,命名為 showSheet。

步驟四:實作點擊事件

- (IBAction)showSheet:(id)sender {
    UIActionSheet *actionSheet = [[UIActionSheet alloc]
            initWithTitle:@"title,nil時不顯示"
                 delegate:self
        cancelButtonTitle:@"取消"
   destructiveButtonTitle:@"確定"
        otherButtonTitles:@"第一項", @"第二項", nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [actionSheet showInView:self.view];
}

參數說明:cancelButtonTitle 與 destructiveButtonTitle 是系統預留的兩個位置,前者是取消、後者是紅色的破壞性操作;otherButtonTitles 接你要自訂的項目,最後一個參數必須是 nil 作為結束標記;showInView: 表示在目前 view 上顯示,另有 showFromToolbar:、showFromTabBar: 等方法可視版面選用。

步驟五:處理選項事件

先封裝一個提示方法,用 UIAlertView 把結果顯示出來,方便觀察:

-(void)showAlert:(NSString *)msg {
    UIAlertView *alert = [[UIAlertView alloc]
            initWithTitle:@"Action Sheet選擇項"
                  message:msg
                 delegate:self
        cancelButtonTitle:@"確定"
        otherButtonTitles: nil];
    [alert show];
}

接著實作委派方法,用 buttonIndex 判斷被點的是哪一項:

-(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:@"取消"];
    }
}

委派協議還有其他可選方法,例如 actionSheetCancel:、willDismissWithButtonIndex:、didDismissWithButtonIndex:,需要處理取消或消失時的收尾就實作它們。

一個實務提醒

buttonIndex 的順序依 addButtonWithTitle:/初始化時傳入參數的先後而定,取消按鈕與破壞性按鈕不一定排在最前,因此正式專案裡建議用列舉常數對照 index,別寫死數字。另外 iOS 8 之後 UIAlertView 與 UIActionSheet 已被標記為廢棄,新專案請改用 UIAlertController 的 actionSheet 樣式。

Copyright © Linux教程網 All Rights Reserved