iOS UIWebView & WKWebView 自动
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];
}