UIActionSheet* sheet = [UIActionSheet new];
sheet.delegate = self;
[sheet addButtonWithTitle:@"action1"];
[sheet addButtonWithTitle:@"action2"];
[sheet addButtonWithTitle:@"Cancel"];
sheet.cancelButtonIndex = 2;
[sheet showInView:self.view];
sheet.tag = 'aaa';
- (void)actionSheet:(UIActionSheet*)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == actionSheet.cancelButtonIndex) {
NSLog(@"pushed Cancel button.");
}
switch (actionSheet.tag) {
case 'aaa':
switch (buttonIndex) {
case 0:
// 0のときはこう!
break;
case 1:
// 1のときはこう!
break;
default:
break;
}
break;
case 'bbb':
switch (buttonIndex) {
case 0:
// 0のときはこう!
break;
case 1:
// 1のときはこう!
break;
default:
break;
}
break;
default:
break;
}
}
UIActionSheet* sheet = [UIActionSheet new];
[sheet addButtonWithTitle:@"action1"
withBlock:^
{
// action1の処理
}];
[sheet addButtonWithTitle:@"action2"
withBlock:^
{
// action2の処理
}];
[sheet addButtonWithTitle:@"Cancel"];
sheet.cancelButtonIndex = 2;
[sheet showInView:self.view];
sheet.tag = 'aaa';
objc_setAssociatedObject がキーポイント
#import <objc/runtime.h>
const char UIActionSheetBlockPropertyPrefix[] = "UIActionSheet+Block.callbackBlocks";
- (NSInteger)addButtonWithTitle:(NSString *)title withBlock:(void (^)(void))block
{
if (!self.delegate) {
self.delegate = self;
}
NSUInteger buttonIndex = [self addButtonWithTitle:title];
NSMutableDictionary *blocks = [self callbackBlocks];
blocks[@(buttonIndex)] = block;
return buttonIndex;
}
- (NSMutableDictionary *)callbackBlocks
{
NSMutableDictionary *blocks = objc_getAssociatedObject(self, UIActionSheetBlockPropertyPrefix);
if (!blocks) {
blocks = [NSMutableDictionary dictionary];
objc_setAssociatedObject(self, UIActionSheetBlockPropertyPrefix, blocks, OBJC_ASSOCIATION_RETAIN);
}
return blocks;
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (actionSheet.cancelButtonIndex == buttonIndex) {
return;
}
NSMutableDictionary *blocks = [actionSheet callbackBlocks];
void (^block)() = blocks[@(buttonIndex)];
if (block) {
block();
}
}
- objc/runtime.h を import してたら注意が必要
- でもきちんと使えば強力
objc_setAssociatedObjectは副作用が少ない
- Xcode 5からは
@import ObjectiveC;って書けるよ!