您可以像这样创建一个类别,然后重用代码:
*.h 文件
@interface UIViewController(Transitions)
- (void) showAlertWithDelegate: (id) delegate;
@end
*.m 文件
-(void) showAlertWithDelegate:(id)delegate {
id _delegate = ( delegate == nil) ? self : delegate;
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: NSLocalizedString(@"Alert Text",@"Alert Text")
message: NSLocalizedString( @"Msg Alert",@"Msg Alert")
delegate:_delegate
cancelButtonTitle:nil
otherButtonTitles: NSLocalizedString(@"OK",@"OK"),nil];
[alert setTag:0]; //so we know in the callback of the alert where we come from - in case we have multiple different alerts
[alert show];
}
//the local callback for the alert - this handles the case when we call the alert with delegate nil
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
D_DBG(@"%i %i",[alertView tag],buttonIndex);
}
在需要警报的 UIViewController 类中导入 *.h 文件。
现在,如果您这样调用:
[self showAlertWithDelegate:nil];
它将显示您的警报,并且代表将被实施
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
当你这样称呼它时,在界面中:
[self showAlertWithDelegate:self];
您需要提供回调
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
在您调用它的类中,因此您可以处理用户按下的任何内容 - 与界面中实现的内容不同。