如何在iOS的ActionSheet加上圖片

本文紀錄新舊版中,Action要帶圖片的作法
1. 舊版UIActionSheet
2. 新版(iOS 8.0) UIAlertController

1. 舊版UIActionSheet
UIActionSheet *actionSheet = [[UIActionSheet alloc]
    initWithTitle:@"我是8.0以下的Action(UIActionSheet)"
    delegate:self
    cancelButtonTitle:NSLocalizedString(@"取消",nil)
    destructiveButtonTitle:nil
    otherButtonTitles:
                              NSLocalizedString(@"選項一",nil),
                              NSLocalizedString(@"選項二",nil),
                              nil];
     
 // 讓第1個action帶圖片
[[[actionSheet valueForKey:@"_buttons"] objectAtIndex:0] setImage:[UIImage imageNamed:@"yourimagename.png"] forState:UIControlStateNormal];
     
actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
[actionSheet showInView:self.view];


2. 新版(iOS 8.0) UIAlertController
UIAlertController * actionSheetNew = [UIAlertController
    alertControllerWithTitle:@"我是8.0以上的Action(UIAlertAction)"
    message:nil
    preferredStyle:UIAlertControllerStyleActionSheet];

// 定義第1個action
UIAlertAction* action1 = [UIAlertAction
    actionWithTitle:@"選項一"
    style:UIAlertActionStyleDefault
    handler:^(UIAlertAction * action)
    {
     //Do some thing here
     [actionSheetNew dismissViewControllerAnimated:YES completion:nil];
     NSLog(@"選項一..");
    }];
 // 讓第1個action帶圖片
[chat setValue:[UIImage imageNamed:@"yourimagename"] forKey:@"image"];

// 定義第2個action
UIAlertAction* action2 = [UIAlertAction
    actionWithTitle:@"選項二"
    style:UIAlertActionStyleDefault
    handler:^(UIAlertAction * action)
    {
     //Do some thing here
     [actionSheetNew dismissViewControllerAnimated:YES completion:nil];
     NSLog(@"選項二..");
    }];

// 定義第3個action
UIAlertAction* action3 = [UIAlertAction
    actionWithTitle:@"取消"
    style:UIAlertActionStyleDefault
    handler:^(UIAlertAction * action)
    {
     //Do some thing here
     [actionSheetNew dismissViewControllerAnimated:YES completion:nil];
     NSLog(@"取消..");
    }];

[actionSheetNew addAction:action1];
[actionSheetNew addAction:action2];
[actionSheetNew addAction:action3];
[self presentViewController:actionSheetNew animated:YES completion:nil];


參考資料
Adding Images to UIActionSheet buttons as in UIDocumentInteractionController
UIActionSheet is deprecated in iOS 8
除了添加圖片,也可以嘗試修改文字顏色,請參考UIAlertController custom font, size, color

沒有留言: