How can I hide keyboard accessory bar in WKWebview? Although there are some resources for UIWebView, I haven\'t been able to find one for WkWebview on Stackoverflow.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillDisappear(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
}
@objc func keyboardWillAppear(_ notification: Notification) {
//Do something here
keyboardShowAndHide(true, notification: notification)
}
@objc func keyboardWillDisappear(_ notification: Notification) {
//Do something here
keyboardShowAndHide(false, notification: notification)
}
func keyboardShowAndHide(_ open: Bool, notification: Notification) {
let userInfo = notification.userInfo ?? [:]
let keyboardFrame = (userInfo[UIResponder.keyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
let height = (keyboardFrame.height + 20) * (open ? 1 : -1)
WKWebView.scrollView.contentInset.bottom += height
WKWebView.scrollView.scrollIndicatorInsets.bottom += height
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
//remove keyboard Listener
NotificationCenter.default.removeObserver(self)
}
This is possible in WKWebView
with a variant of the method for swizzling out the inputAccessoryView on UIWebView.
First, add this little class:
@interface _NoInputAccessoryView : NSObject
@end
@implementation _NoInputAccessoryView
- (id)inputAccessoryView {
return nil;
}
@end
Next, add this method:
- (void)removeInputAccessoryViewFromWKWebView:(WKWebView *)webView {
UIView *targetView;
for (UIView *view in webView.scrollView.subviews) {
if([[view.class description] hasPrefix:@"WKContent"]) {
targetView = view;
}
}
if (!targetView) {
return;
}
NSString *noInputAccessoryViewClassName = [NSString stringWithFormat:@"%@_NoInputAccessoryView", targetView.class.superclass];
Class newClass = NSClassFromString(noInputAccessoryViewClassName);
if(newClass == nil) {
newClass = objc_allocateClassPair(targetView.class, [noInputAccessoryViewClassName cStringUsingEncoding:NSASCIIStringEncoding], 0);
if(!newClass) {
return;
}
Method method = class_getInstanceMethod([_NoInputAccessoryView class], @selector(inputAccessoryView));
class_addMethod(newClass, @selector(inputAccessoryView), method_getImplementation(method), method_getTypeEncoding(method));
objc_registerClassPair(newClass);
}
object_setClass(targetView, newClass);
}
Then all you have to do is call that method and pass in your WKWebView
:
[self removeInputAccessoryViewFromWKWebView:webView];
Note: I do not yet know for sure if this will pass app review, but it is extremely similar to the same code I used for UIWebView
, and that did pass review.
Update: This code is in an app that has passed App Store review.