webview去掉自带的done按钮栏

需求:去掉键盘自带的done按钮所在的工具栏

UIWebView
// 使用
[self hideKeyboardShortcutBar:self.webView];
// 实现:代码如下
- (void) hideKeyboardShortcutBar: (UIView *)view
{
    for (UIView *sub in view.subviews) {
        [self hideKeyboardShortcutBar:sub];
        if ([NSStringFromClass([sub class]) isEqualToString:@"UIWebBrowserView"]) {
            
            Method method = class_getInstanceMethod(sub.class, @selector(inputAccessoryView));
            IMP newImp = imp_implementationWithBlock(^(id _s) {
                if ([sub respondsToSelector:@selector(inputAssistantItem)]) {
                    UITextInputAssistantItem *inputAssistantItem = [sub inputAssistantItem];
                    inputAssistantItem.leadingBarButtonGroups = @[];
                    inputAssistantItem.trailingBarButtonGroups = @[];
                }
                return nil;
            });
            method_setImplementation(method, newImp);
            
        }
    }
}
WkWebView
// 使用
[self hideWKWebviewKeyboardShortcutBar:self.webView];
// 实现
// 步骤一:创建一个_NoInputAccessoryView
@interface _NoInputAccessoryView : NSObject
@end
@implementation _NoInputAccessoryView
- (id)inputAccessoryView {
    return nil;
}
@end
// 步骤二:去掉wkwebviewedone工具栏
- (void) hideWKWebviewKeyboardShortcutBar:(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);
}

你可能感兴趣的:(webview去掉自带的done按钮栏)