我将使用GCD
&blocks
发布一个非常简单的解决方案(GCD 部分是为了以防万一警报视图是在另一个线程上创建的,然后是主线程,回调应该可以安全地在主线程上执行)。请记住,我只是在 5 分钟内编写了此代码,因此您绝对应该努力改进代码。有点难看的一件事是在我的子类中覆盖的委托参数。子类的接口可以稍微改变一下,以使发生的事情更加明显......
无论如何,这里...
首先创建一个 的子类UIAlertView
,让它看起来有点像下面...
@interface FSAlertView () <UIAlertViewDelegate>
@property (nonatomic, copy) void (^dismissHandler)(NSInteger buttonIndex);
@end
@implementation FSAlertView
@synthesize dismissHandler = _dismissHandler;
- (void)showWithDismissHandler:(void (^)(NSInteger buttonIndex))dismissHandler
{
self.dismissHandler = dismissHandler;
self.delegate = self;
[self show];
}
// Alert view delegate
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
dispatch_async(dispatch_get_main_queue(), ^ {
if (_dismissHandler)
{
_dismissHandler(buttonIndex);
}
});
}
现在在应用程序中,我们可以创建警报视图,如下所示...
FSAlertView *alert1 = [[FSAlertView alloc] initWithTitle:@"Alert 1"
message:@"Some message"
delegate:nil
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Show 2nd Alert", nil];
[alert1 showWithDismissHandler:^ (NSInteger buttonIndex) {
NSLog(@"button pressed: %d", buttonIndex);
if (buttonIndex == 1)
{
UIAlertView *alert2 = [[UIAlertView alloc] initWithTitle:@"Alert 2"
message:@"Hi!"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert2 show];
}
}];