美文网首页
iOS UIWebView & WKWebView 自动

iOS UIWebView & WKWebView 自动

作者: 忻凯同学 | 来源:发表于2019-02-21 11:12 被阅读6次

1. UIWebView

查阅UIWebView的API会发现有 keyboardDisplayRequiresUserAction 这个属性,默认是YES,意思是键盘的展示必须由用户的行为决定的,也就是说只有用户点击才会弹起键盘。

该属性设置为NO,实现UIWebView自动弹起软键盘。

webView.keyboardDisplayRequiresUserAction = NO;

2. WKWebView

WKWebView并没有像UIWebView那样有现成的属性,需要利用runtime实现。

1. 导入头文件:

#import <objc/runtime.h>

2. 实现方法:

- (void)allowDisplayingKeyboardWithoutUserAction {

    Class class = NSClassFromString(@"WKContentView");

    NSOperatingSystemVersion iOS_11_3_0 = (NSOperatingSystemVersion){11, 3, 0};

    if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion: iOS_11_3_0]) {

        SEL selector = sel_getUid("_startAssistingNode:userIsInteracting:blurPreviousNode:changingActivityState:userObject:");

        Method method = class_getInstanceMethod(class, selector);

        IMP original = method_getImplementation(method);

        IMP override = imp_implementationWithBlock(^void(id me, void* arg0, BOOL arg1, BOOL arg2, BOOL arg3, id arg4) {

            ((void (*)(id, SEL, void*, BOOL, BOOL, BOOL, id))original)(me, selector, arg0, TRUE, arg2, arg3, arg4);

        });

        method_setImplementation(method, override);

    } else {

        SEL selector = sel_getUid("_startAssistingNode:userIsInteracting:blurPreviousNode:userObject:");

        Method method = class_getInstanceMethod(class, selector);

        IMP original = method_getImplementation(method);

        IMP override = imp_implementationWithBlock(^void(id me, void* arg0, BOOL arg1, BOOL arg2, id arg3) {

            ((void (*)(id, SEL, void*, BOOL, BOOL, id))original)(me, selector, arg0, TRUE, arg2, arg3);

        });

        method_setImplementation(method, override);

    }

}

3. 调用方法

#pragma mark -- WKScriptMessageHandler

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {

    // 自动弹起键盘       

    [self allowDisplayingKeyboardWithoutUserAction];

}

相关文章

网友评论

      本文标题:iOS UIWebView & WKWebView 自动

      本文链接:https://www.haomeiwen.com/subject/byfryqtx.html