iOS UIWebView重写或者监听js Alter/Confirm/Prompt函数

最近公司在开发web型的app,涉及许多交互,刚好,我遇到js中 的Alter/Confirm/Prompt三个弹框提示函数的坑,今天记录解决的办法下来,供大家使用。

1、在开发过程中,前端使用了他们自己的弹框框架,结果在iOS和Android端展示这样子,多了http。

这里写图片描述

2、为了解决这样的问题,百度了许多,最终借助百度上的资料和官方文档,试验成功了。
3、其实不难解决这个问题,新建个UIWebView类别,在m文件写上如下代码,即可。

- (void)webView:(UIWebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(CGRect *)frame {


    UIAlertView* customAlert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];

    [customAlert show];


}
static BOOL diagStat = NO;

static NSInteger bIdx = -1;

- (BOOL)webView:(UIWebView *)sender runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(id)frame{

    diagStat = NO;

    bIdx = -1;

    UIAlertView *confirmDiag = [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                          message:message
                                                         delegate:self
                                                cancelButtonTitle:@"取消"
                                                otherButtonTitles:@"确定",  nil];

    [confirmDiag show];

    while (bIdx==-1) {
        //[NSThread sleepForTimeInterval:0.2];
        [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1f]];
    }
    if (bIdx == 0){//取消;
        diagStat = NO;
    }
    else if (bIdx == 1) {//确定;
        diagStat = YES;
    }
    return diagStat;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    bIdx = buttonIndex;
}

- (NSString *) webView:(UIWebView *)view runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)text initiatedByFrame:(id)frame{

    diagStat = NO;

    bIdx = -1;

    UIAlertView *confirmDiag = [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                          message:prompt
                                                         delegate:self
                                                cancelButtonTitle:@"取消"
                                                otherButtonTitles:@"确定",  nil];


    [confirmDiag setAlertViewStyle:UIAlertViewStylePlainTextInput];

    UITextField *textField = [confirmDiag textFieldAtIndex:0];
    textField.placeholder = @"请输入信息";
    textField.keyboardType = UIKeyboardTypeDefault;


    [confirmDiag show];

    while (bIdx==-1) {
        //[NSThread sleepForTimeInterval:0.2];
        [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1f]];
    }
    if (bIdx == 0){//取消;
        diagStat = NO;
    }
    else if (bIdx == 1) {//确定;
        diagStat = YES;
    }
    return textField.text;


}

效果如下:

这里写图片描述

有用,顶下

猜你喜欢

转载自blog.csdn.net/qq_33432683/article/details/60144867