MyAlertView(UIAlertView的子类)具有以下方法:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (self.clickedButtonAtIndexBlock != NULL)
        self.clickedButtonAtIndexBlock(buttonIndex);
}


我的问题是在创建警报视图时如何定义回调?显然这是错误的:

alert.clickedButtonAtIndexBlock = ^{
    NSLog(@"clicked: %d", buttonIndex);
}

最佳答案

尝试做这样的事情(我还没有测试):

.h
typedef void (^MyClickedIndexBlock)(NSInteger index);

@interface YouInterface : YourSuperclass
@property (nonatomic, strong) MyClickedIndexBlock clickedIndexBlock;
@end

.m
//where you have to call the block
if (self.clickedIndexBlock != nil)
    self.clickedIndexBlock(buttonIndex);

// where you want to receive the callback
alert.clickedIndexBlock = ^(NSInteger index){
    NSLog(@"%d", index);
};

10-05 17:58