提前致谢。
您可以通过子类化 UIWebView 并覆盖来做到这一点(无需自己向菜单控制器添加任何内容):
-(BOOL) canPerformAction:(SEL)action withSender:(id)sender
并检查选择器是否为
selectAll:
-(BOOL) canPerformAction:(SEL)action withSender:(id)sender {
if (action == @selector(selectAll:)) {
return YES;
} else {
return [super canPerformAction:action withSender:sender];
}
}
这将在保留菜单上显示全选选项。然而,这不是 webView 的默认行为,虽然当您按全选时应用程序不会崩溃,但按它不会执行任何操作。
您甚至无法创建 selectAll 方法,然后选择 webview 中的所有内容,因为 javascript 方法
.select()
不适用于 Mobile Safari/UIWebView。
selectAll
类别为不可编辑的
webView
实现
UIWebView
行为(相当于 Apple Mail.app 中的行为)。主要思想是使用提示,
UIWebBrowserView
是
UIWebView
的子视图,是
UIWebDocumentView
的子类,它符合
UITextInputPrivate
协议,相当于公共
UITextInput
协议
// UIWebView+SelectAll.h
// Created by Alexey Matveev on 28.03.15.
// Copyright (c) 2015 Alexey Matveev. All rights reserved.
@interface UIWebView (SelectAll)
+ (void)setEnableSelectAll:(BOOL)enabled;
@end
#import "UIWebView+SelectAll.h"
#import <objc/runtime.h>
/*
UIWebDocumentView is the superclass for UIWebBrowserView.
UIWebDocumentView conforms UITextInputPrivate protocol which is identival to UITextInput
*/
static IMP canPerformActionWithSenderImp;
@implementation UIWebView (SelectAll)
@dynamic enableSelectAll;
- (BOOL)customCanPerformAction:(SEL)action withSender:(id)sender
{
if (action == @selector(selectAll:)) {
return ! self.isSelectedAll;
}
else {
BOOL(*imp)(id, SEL, SEL, id) = (BOOL(*)(id, SEL, SEL, id))canPerformActionWithSenderImp;
return imp(self, @selector(canPerformAction:withSender:), action, sender);
}
}
- (void)selectAll:(id)sender
{
[self.browserView selectAll:sender];
}
- (UIView<UITextInput> *)browserView
{
UIView *browserView;
for (UIView *subview in self.scrollView.subviews) {
if ([subview isKindOfClass:NSClassFromString(@"UIWebBrowserView")]) {
browserView = subview;
break;
}
}
return (UIView<UITextInput> *)browserView;
}
- (BOOL)isSelectedAll
{
UITextRange *currentRange = self.browserView.selectedTextRange;
if ([self.browserView comparePosition:currentRange.start toPosition:self.browserView.beginningOfDocument] == NSOrderedSame) {
if ([self.browserView comparePosition:currentRange.end toPosition:self.browserView.endOfDocument] == NSOrderedSame) {
return YES;
}
}
return NO;
}
+ (void)setEnableSelectAll:(BOOL)enabled
{
SEL canPerformActionSelector = @selector(canPerformAction:withSender:);
if (!canPerformActionWithSenderImp) {
canPerformActionWithSenderImp = [self instanceMethodForSelector:canPerformActionSelector];
}
IMP newCanPerformActionWithSenderImp = enabled ? [self instanceMethodForSelector:@selector(customCanPerformAction:withSender:)] : canPerformActionWithSenderImp;
Method canPerformActionMethod = class_getInstanceMethod([self class], canPerformActionSelector);
class_replaceMethod([self class], canPerformActionSelector, newCanPerformActionWithSenderImp, method_getTypeEncoding(canPerformActionMethod));
}
@end
当然,你可以使用全局方法swizzling for
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender;
以标准方式,但它将不可逆转地影响项目中的所有 webView。