我编写了一个简单的类 LMSVBlocks 来轻松显示警报并在 1 行中获取块回调。希望您会发现它对此有用
https://github.com/sourabhverma/LMSVBlocks
概念:要使 UIAlertView 块兼容,您需要另一个类(例如 LMSVBlockAlert)来处理委托方法,当 UIAlertView 委托将给出回调时,LMSVBlockAlert 类可以在块中发送回调。
代码:
(LMSVBlockAlert.m)
将 LMSVBlockAlert 的所有实例维护在一个数组中,以便它们具有强引用
static NSMutableArray *_LMSVblockHandlersArray = nil;
将块处理程序保留在 LMSVBlockAlert
@interface LMSVBlockAlert() <UIAlertViewDelegate>
@property (nonatomic, copy) void (^cancelCompletionBlock)();
@property (nonatomic, copy) void (^confirmCompletionBlock)();
@end
当触发新警报时,创建具有 UIAlertView 和委托回调的 LMSVBlockAlert 新实例
+(LMSVBlockAlert*)newInstance{
LMSVBlockAlert *newIns = [[LMSVBlockAlert alloc] init];
[LMSVBlockAlert updateHandlerArrayWith:newIns];
return newIns;
}
当在 LMSVBlockAlert 中触发警报委托时,发送回调以阻止并从内存中清除它
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
switch (buttonIndex) {
case 0://Cancel
{
if(_cancelCompletionBlock){
_cancelCompletionBlock();
}
}
break;
case 1://OK
{
if(_confirmCompletionBlock){
_confirmCompletionBlock(alertView);
}
}
break;
default:
break;
}
[_LMSVblockHandlersArray removeObject:self];
}
现在你可以有两个简单的方法可以给你 UIAlertView 回调
+(UIAlertView*)promptAlertTwoBtn:(NSString*)msg title:(NSString*)title onCancel:(void (^)())onCancel onConfirm:(void (^)())onConfirm{
return [[LMSVBlockAlert newInstance] showAlertMainWithTitle:title msg:msg onCancel:^{
onCancel();
} onConfirm:^(UIAlertView *alertView) {
onConfirm();
}];
}
-(UIAlertView*)showAlertMainWithTitle:(NSString*)title msg:(NSString*)msg onCancel:(void (^)())onCancel onConfirm:(void (^)(UIAlertView*))onConfirm{
UIAlertView *newAlert = nil;
newAlert = [[UIAlertView alloc]
initWithTitle:title
message:msg
delegate:self
@"Cancel"
otherButtonTitles:@"Confirm", nil];
[newAlert show];
self.cancelCompletionBlock = onCancel;
self.confirmCompletionBlock = onConfirm;
return newAlert;
}
最后
希望你发现它有用..