[iOS]ユーザに選択させる(UIActionSheet) | Cocoa練習帳

[iOS]ユーザに選択させる(UIActionSheet)

前回のアラートは、ユーザに情報を伝える為のもの。今回のアクション・シートはユーザに選択させる為のものだ。




ビューコントローラにUIActionSheetDelegateプロトコルを設定する。




@interface ViewController : UIViewController <UIActionSheetDelegate>
@end



アクションシートを表示させる。




@implementation ViewController
 
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UIActionSheet   *actionSheet = [[UIActionSheet alloc] initWithTitle:@"My Action Sheet"
                                                               delegate:self
                                                      cancelButtonTitle:@"Cancel"
                                                 destructiveButtonTitle:@"destructive button"
                                                      otherButtonTitles:@"Button 1",
                                                                        @"Button 2", 
                                                                        nil];
    [actionSheet showInView:self.view];
}
 
@end



アラートと同様にアクション・シートもデリゲートのメソッドでボタン押下に対応する。




@implementation ViewController
  
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"%s index(%d)", __func__, (int)buttonIndex);
}
 
- (void)actionSheetCancel:(UIActionSheet *)actionSheet
{
    NSLog(@"%s", __func__);
}
 
@end



実行。




アクションシート




アクション・シートでは、追加するボタンの個数は可変だ。画面に収まりきれなく個数を指定した場合は、どうなるのだろうか?




@implementation ViewController
 
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UIActionSheet   *actionSheet = [[UIActionSheet alloc] initWithTitle:@"My Action Sheet"
                                                               delegate:self
                                                      cancelButtonTitle:@"Cancel"
                                                 destructiveButtonTitle:@"destructive button"
                                                      otherButtonTitles:@"Button 1",
                                                                        @"Button 2",
                                                                        @"Button 3",
                                                                        @"Button 4",
                                                                        @"Button 5",
                                                                        @"Button 6", 
                                                                        nil];
    [actionSheet showInView:self.view];
}
 
@end



ピッカー




なんと、ボタンの部分がピッカーになっている!




第50回関東Cocoa勉強会で@saeki24hさんが、自身が発見されたアクション・シートのバグを発表されていましたが、その時はボタンの個数が増えてピッカーになった際に、cancelボタンとdestructiveボタンの順番が変わって、その際、インデックスがおかしくなっていたが、iOS 5.1で修正されたのか、ボタンの順番が変わらず、その為か、インデックスは正しい値のようだ。






関連情報
UIActionSheet Class Reference

UIActionSheetDelegate Protocol Reference