UIAlertViewで同期する方法
ひさびさの投稿。でも、あくまでもメモっす。°₊·ˈ∗( ˃̶᷇ ‧̫ ˂̶᷆ )∗ˈ‧₊°
UIAlertViewって、デリゲートを使用するので
同期とれないですよね。
そこで、クラスをつくり、中でBlocksを使用して、そのまま返すって方法です。
文字では伝わらないんでソースでみてくんろぉ〜ヽ( ゜ 3゜)ノ
CustomAlertView.h
#import <Foundation/Foundation.h>
typedef void (^didDismissBlocksType)(NSInteger buttonIndex);
@interface CustomAlertView : UIAlertView <UIAlertViewDelegate>
- (id)initWithTitle:(NSString *)title
message:(NSString *)message
didDismissBlocks:(didDismissBlocksType)didDismissBlocks
cancelButtonTitle:(NSString *)cancelButtonTitle
otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION;
@end
CustomAlertView.m
#import "CustomAlertView.h"
@interface CustomAlertView()
{
didDismissBlocksType didDismissBlocks;
}
@end
@implementation CustomAlertView
- (id)initWithTitle:(NSString *)title
message:(NSString *)message
didDismissBlocks:(didDismissBlocksType)didDismiss
cancelButtonTitle:(NSString *)cancelButtonTitle
otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION
{
self = [super init];
if (self) {
self.delegate = self;
}
self.title = title;
self.message=message;
didDismissBlocks = didDismiss;
va_list arguments;
va_start(arguments, otherButtonTitles);
NSString* value = otherButtonTitles;
// 可変長引数が nil になるまで繰り返す
while (value)
{
[self addButtonWithTitle:value];
// 次の引数を取得
value = va_arg(arguments, typeof(NSString*));
}
// 最後に可変長引数の扱いが終わったことを va_end 関数を使って伝えます。
va_end(arguments);
[self addButtonWithTitle:cancelButtonTitle];
return self;
}
//アラートが消えてから呼ばれる
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
if(didDismissBlocks != nil)
{
didDismissBlocks(buttonIndex);
}
}
@end
使い方。
CustomAlertView *alertView
= [[CustomAlertView alloc] initWithTitle:@"aaaa"
message:@"Message"
didDismissBlocks:^(NSInteger buttonIndex){
switch (buttonIndex) {
case 0:
//1番目のボタンが押されたときの処理を記述する
NSLog(@"test2Action:ほえほえ1");
break;
case 1:
//2番目のボタンが押されたときの処理を記述する
NSLog(@"test2Action:ほえほえ2");
break;
}
}
cancelButtonTitle:@"キャンセル"
otherButtonTitles:@"ボタン1" ,@"ボタン2",@"ボタン3" ,nil
];
[alertView show];
動作は、自分らで確かめて下さいw
適当にコピペだから文字の大きさ色がぐちゃぐちゃ。あーあ(・_・、)グスン
まぁ、私のブログはこんなもんです。。。。。。