0x00 方法一
通过 JavaScript 注入来实现:
NSString *js = @"document.body.style.userSelect = 'none'; document.body.style.webkitUserSelect = 'none';";
WKUserContentController *ctrl = [[WKUserContentController alloc] init];
WKUserScript *script = [[WKUserScript alloc] initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
[ctrl addUserScript:script];
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
config.userContentController = ctrl;
WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
webView.scrollView.minimumZoomScale = 1.0;
webView.scrollView.maximumZoomScale = 1.0;
0x01 方法二
在加载完成后,注入 JS 代码
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
// 注入JavaScript代码来禁用文字选择
let script = """
document.body.style.webkitUserSelect = 'none';
document.body.style.userSelect = 'none';
"""
webView.evaluateJavaScript(script, completionHandler: nil)
}
0x03
重写 WKWebView 的 canPerformAction
方法来禁用文字选择和上下文菜单
class NoSelectWebView: WKWebView {
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
// 禁用文字选择和上下文菜单
if action == #selector(UIResponderStandardEditActions.copy(_:)) ||
action == #selector(UIResponderStandardEditActions.select(_:)) ||
action == #selector(UIResponderStandardEditActions.selectAll(_:)) {
return false
}
return super.canPerformAction(action, withSender: sender)
}
}