利用iOS原生代码为壳,加载Html代码的过程中,进行alert或者confirm进行信息提示的时候,会出现下图的情况:
这个时候,就需要捕捉alert或者confirm的事件,以便处理提示框显示的样式。
捕捉alert或者confirm的事件,代码如下:
@implementation UIWebView (JavaScriptAlert)
- (void)webView:(UIWebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(id)frame {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *ensureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:ensureAction];
UIViewController *rootViewController = [UIApplication sharedApplication].windows.firstObject.rootViewController;
[rootViewController presentViewController:alertController animated:YES completion:nil];
}
static BOOL clickState = NO;
static NSInteger btnIndex = -1;
- (BOOL)webView:(UIWebView *)sender runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(id)frame {
NSString *otherButtonText = @"确定";
NSString *cancelButtonText = @"取消";
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelButtonText style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[self clickActionButton:0];
}];
UIAlertAction *ensureAction = [UIAlertAction actionWithTitle:otherButtonText style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[self clickActionButton:1];
}];
[alertController addAction:cancelAction];
[alertController addAction:ensureAction];
UIViewController *rootViewController = [UIApplication sharedApplication].windows.firstObject.rootViewController;
[rootViewController presentViewController:alertController animated:YES completion:nil];
btnIndex = -1;
while (btnIndex == -1) {
[[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1f]];
}
if (btnIndex == 0){
// 取消
clickState = NO;
}else if (btnIndex == 1) {
// 确定
clickState = YES;
}
return clickState;
}
- (void)clickActionButton:(NSInteger)buttonIndex{
btnIndex = buttonIndex;
}
@end
经测试结果如图所示: