我似乎无法从UIWebView中删除Bold,Italic和Underline选项.为什么这不可能?
CustomWebView.h:
#import <UIKit/UIKit.h>
@interface CustomUIWebView : UIWebView
@end
Run Code Online (Sandbox Code Playgroud)
CustomWebView.m:
#import <Foundation/Foundation.h>
#import "CustomUIWebView.h"
@implementation CustomUIWebView
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
return NO;
return [super canPerformAction:action withSender:sender];
}
@end
Run Code Online (Sandbox Code Playgroud)
为了解决这个问题,我进行了很多研究,终于找到了解决方案。我首先虽然覆盖- (BOOL)canPerformAction:(SEL)action withSender:(id)sender包含UIViewController将UIWebView足以防止文本样式选项显示。但不幸的是,这并不像看起来那么容易。
这样做的主要原因是我们必须覆盖主要第一响应者canPerformAction的。控制器的呼叫通知我们这是实际的主要第一响应者。我们想要子类化,但由于它是一个私有类,我们的应用程序可能会在审核过程中被苹果拒绝。@Shayan RC 的这个答案建议执行方法调配,以允许在不进行子类化的情况下覆盖此方法(从而防止 App Store 拒绝)。[[[UIApplication sharedApplication] keyWindow] performSelector:@selector(firstResponder)]UIWebBrowserViewUIWebBrowserViewUIWebBrowserView
这个想法是添加一个新方法来替换canPerformAction. 我创建了一个数组,其中包含我们想要保留在菜单中的所有方法签名。要删除样式选项,我们只需不要添加@"_showTextStyleOptions:"到该数组中即可。添加您想要显示的所有其他方法签名(我添加了一个NSLog签名,以便您可以选择您想要的)。
- (BOOL) mightPerformAction:(SEL)action withSender:(id)sender {
NSLog(@"action : %@", NSStringFromSelector(action));
NSArray<NSString*> *selectorsToKeep = @[@"cut:", @"copy:", @"select:", @"selectAll:", @"_lookup:"]; //add in this array every action you want to keep
if ([selectorsToKeep containsObject:NSStringFromSelector(action)]) {
return YES;
}
return NO;
}
Run Code Online (Sandbox Code Playgroud)
现在我们可以执行方法调配来调用以前的方法而不是canPerformAction使用以下方法(来自@Shayan RC的答案)。这将需要添加#import <objc/runtime.h>.
- (void) replaceUIWebBrowserView: (UIView *)view {
//Iterate through subviews recursively looking for UIWebBrowserView
for (UIView *sub in view.subviews) {
[self replaceUIWebBrowserView:sub];
if ([NSStringFromClass([sub class]) isEqualToString:@"UIWebBrowserView"]) {
Class class = sub.class;
SEL originalSelector = @selector(canPerformAction:withSender:);
SEL swizzledSelector = @selector(mightPerformAction:withSender:);
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(self.class, swizzledSelector);
//add the method mightPerformAction:withSender: to UIWebBrowserView
BOOL didAddMethod =
class_addMethod(class,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));
//replace canPerformAction:withSender: with mightPerformAction:withSender:
if (didAddMethod) {
class_replaceMethod(class,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
最后,viewDidLoad像这样调用前面的方法[self replaceUIWebBrowserView:_webView]:
方法调配似乎很难,但它允许您将代码保留在视图控制器中。如果您在实现以前的代码时遇到任何困难,请告诉我。
WKWebView注意:这种行为比使用更容易实现UIWebView,并且UIWebView已被弃用,您应该真正考虑切换到WKWebView。