ios 如何禁用文本选择WKWebView编程?

eeq64g8w  于 2023-05-19  发布在  iOS
关注(0)|答案(2)|浏览(128)

问题

您可以在WKWebView中选择文本。

期望行为

您应该根本无法在Web视图中选择文本。

我所尝试的

1.使用evaluateJavaScript:completionHandler:加载NSString * jsCallBack = @"window.getSelection().removeAllRanges();";
1.使用"document.documentElement.style.webkitUserSelect='none'"执行上述操作

  1. webView.configuration.selectionGranularity = nil; <--这个没有意义,因为selectionGranularity只能接受两个预定义的值,但值得一试。
    1.尝试在故事板中寻找解决方案,但无法找到不会禁用用户交互的解决方案。

我不能做的事

改变HTML/CSS代码是不是一个选项在这个时候,如果我可以改变它this answer可能会工作。

2j4z5cfb

2j4z5cfb1#

半私有灰色区域解决方案依赖于私有Web视图层次结构及其点击手势。作为奖励不依赖于私有类和方法符号,但如果点击手势的顺序会改变,它会打破。

@import WebKit;
@interface ViewController ()

@property(null_resettable, nonatomic,strong) WKWebView *view;
@end

@implementation ViewController

@dynamic view;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view = [WKWebView new];

    for (UIView *view in self.view.subviews) {
        for (UIView *innerView in view.subviews) {
            if (innerView.gestureRecognizers.count > 0) {
                NSMutableArray<UIGestureRecognizer*> *gestureRecognizers = [innerView.gestureRecognizers mutableCopy];
                [gestureRecognizers removeObjectAtIndex:0];
                innerView.gestureRecognizers = [gestureRecognizers copy];
            }
        }
    }

    [self.view loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://stackoverflow.com/questions/43227437/how-to-disable-text-selection-wkwebview-programatically"]]];
}
@end
f45qwnt8

f45qwnt82#

**// add gesture on viewDidLoad**
override func viewDidLoad() 
{
    super.viewDidLoad()
    let longPress:UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: nil, action: nil)
    longPress.minimumPressDuration = 0.3
    webView.addGestureRecognizer(longPress)
}

**//also inherit the UIGestureRecognizerDelegate**

class ViewController: UIViewController, UIGestureRecognizerDelegate {
}

相关问题