UIWebView 加载本地的 HTML 时,HTML 中的锚点是无效的,需要特殊处理,可以通过 JavaScript 来实现。

1
2
3
4
5
6
7
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
let urlString = request.url!.absoluteString
let anchor = urlString.suffix(from: urlString.range(of: "#")!.upperBound)
let jsString = "document.getElementById('\(anchor)').scrollIntoView()"
webView.stringByEvaluatingJavaScript(from: jsString)
return false
}

参考