You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中含WKWebView的List视图性能问题及优化实现求助

嘿,我来帮你解决这个SwiftUI里用WKWebView做List条目时的性能和滚动问题!

首先咱们得先搞清楚问题出在哪:

  1. WKWebView的频繁创建/销毁:SwiftUI的List基于UITableView,会复用cell,但你的PostWebView每次都会新建一个WKWebView——这可是个资源大户,创建和加载都很耗性能,直接导致滚动卡顿、内容加载异常。
  2. 固定高度的布局问题:你给PostWebView设了固定的50高度,但HTML内容实际高度可能不是这个数,这会让布局混乱,滚动时出现内容消失/显示不全的情况。
  3. 那些WebFilter日志:这个其实是系统级的正常输出,和你的问题没关系,是WebKit的内容过滤机制在打日志,完全可以忽略它。

接下来给你两个优化方案,从简单到进阶:


方案一:优化WKWebView的内容更新与自适应高度

这个方案不需要改List的底层逻辑,只需要调整PostWebView,让它可以复用实例并动态调整高度:

修改PostWebView

import SwiftUI
import WebKit

struct PostWebView: UIViewRepresentable {
    let text: String
    @Binding var contentHeight: CGFloat // 绑定内容高度,让SwiftUI能动态调整布局
    
    class Coordinator: NSObject, WKNavigationDelegate {
        var parent: PostWebView
        
        init(_ parent: PostWebView) {
            self.parent = parent
        }
        
        // 页面加载完成后获取实际内容高度
        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
            webView.evaluateJavaScript("document.body.scrollHeight") { result, error in
                if let height = result as? CGFloat {
                    DispatchQueue.main.async {
                        self.parent.contentHeight = height
                    }
                }
            }
        }
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    func makeUIView(context: Context) -> WKWebView {
        let webConfiguration = WKWebViewConfiguration()
        let webview = WKWebView(frame: .zero, configuration: webConfiguration)
        webview.scrollView.bounces = false
        webview.scrollView.isScrollEnabled = false
        webview.navigationDelegate = context.coordinator
        webview.backgroundColor = .clear
        return webview
    }
    
    func updateUIView(_ uiView: WKWebView, context: Context) {
        // 只有内容变化时才重新加载,避免重复开销
        let htmlStart = "<HTML><HEAD><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, shrink-to-fit=no, maximum-scale=1.0, user-scalable=no\"></HEAD><BODY>"
        let htmlEnd = "</BODY></HTML>"
        let htmlString = "\(htmlStart)\(text)\(htmlEnd)"
        
        uiView.evaluateJavaScript("document.body.innerHTML") { currentHtml, _ in
            if currentHtml as? String != self.text {
                uiView.loadHTMLString(htmlString, baseURL: nil)
            }
        }
    }
}

修改ContentView,支持动态高度

struct ContentView: View {
    // 存储每个帖子的内容高度,初始值设为0
    @State private var contentHeights = Array(repeating: CGFloat(0), count: 21)
    let htmlText = "<p>This is the paragraph</p><p>Add more content here to test height adaptation!</p>"
    
    init() {
        UITableView.appearance().separatorStyle = .none
        UITableViewCell.appearance().selectionStyle = .none
        UITableView.appearance().backgroundColor = .clear
    }
    
    var body: some View {
        List {
            ForEach(0..<21, id: \.self) { index in
                VStack {
                    PostWebView(text: htmlText, contentHeight: $contentHeights[index])
                        .frame(height: contentHeights[index])
                    Divider()
                }
                .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
                .listRowBackground(Color.clear)
            }
        }
    }
}

方案二:进阶优化——利用UITableView的Cell复用

如果方案一的性能还不够,咱们可以直接用UIKit的UITableView来实现,彻底利用它的cell复用机制,每个cell复用同一个WKWebView,大幅降低资源消耗:

自定义UITableViewCell与代理

import SwiftUI
import WebKit

// 自定义包含WKWebView的TableViewCell
class PostTableViewCell: UITableViewCell {
    static let reuseIdentifier = "PostCell"
    var webView: WKWebView!
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupWebView()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupWebView()
    }
    
    private func setupWebView() {
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: contentView.bounds, configuration: webConfiguration)
        webView.scrollView.bounces = false
        webView.scrollView.isScrollEnabled = false
        webView.backgroundColor = .clear
        webView.translatesAutoresizingMaskIntoConstraints = false
        contentView.addSubview(webView)
        
        // 约束让WebView充满cell
        NSLayoutConstraint.activate([
            webView.topAnchor.constraint(equalTo: contentView.topAnchor),
            webView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
            webView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
            webView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
        ])
    }
    
    // 加载HTML并返回内容高度
    func loadHTML(_ html: String, completion: @escaping (CGFloat) -> Void) {
        let htmlStart = "<HTML><HEAD><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, shrink-to-fit=no, maximum-scale=1.0, user-scalable=no\"></HEAD><BODY>"
        let htmlEnd = "</BODY></HTML>"
        let htmlString = "\(htmlStart)\(html)\(htmlEnd)"
        
        webView.loadHTMLString(htmlString, baseURL: nil)
        
        // 用临时代理获取高度
        let delegate = PostCellNavigationDelegate(completion: completion)
        webView.navigationDelegate = delegate
    }
}

// 用于获取WebView内容高度的导航代理
class PostCellNavigationDelegate: NSObject, WKNavigationDelegate {
    private let completion: (CGFloat) -> Void
    
    init(completion: @escaping (CGFloat) -> Void) {
        self.completion = completion
        super.init()
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        webView.evaluateJavaScript("document.body.scrollHeight") { result, _ in
            if let height = result as? CGFloat {
                DispatchQueue.main.async {
                    self.completion(height)
                }
            }
        }
    }
}

包装UITableView到SwiftUI

struct PostListView: UIViewControllerRepresentable {
    let htmlText: String
    let itemCount: Int
    
    func makeUIViewController(context: Context) -> UITableViewController {
        let tableView = UITableView()
        tableView.separatorStyle = .none
        tableView.backgroundColor = .clear
        tableView.register(PostTableViewCell.self, forCellReuseIdentifier: PostTableViewCell.reuseIdentifier)
        
        let vc = UITableViewController(style: .plain)
        vc.tableView = tableView
        vc.tableView.dataSource = context.coordinator
        vc.tableView.delegate = context.coordinator
        
        return vc
    }
    
    func updateUIViewController(_ uiViewController: UITableViewController, context: Context) {
        uiViewController.tableView.reloadData()
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(parent: self)
    }
    
    class Coordinator: NSObject, UITableViewDataSource, UITableViewDelegate {
        let parent: PostListView
        private var cellHeights = [IndexPath: CGFloat]() // 存储每个cell的高度
        
        init(parent: PostListView) {
            self.parent = parent
            super.init()
        }
        
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            parent.itemCount
        }
        
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: PostTableViewCell.reuseIdentifier, for: indexPath) as! PostTableViewCell
            cell.loadHTML(parent.htmlText) { [weak self] height in
                guard let self = self else { return }
                self.cellHeights[indexPath] = height
                // 更新cell高度
                tableView.beginUpdates()
                tableView.endUpdates()
            }
            return cell
        }
        
        func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            return cellHeights[indexPath] ?? UITableView.automaticDimension
        }
    }
}

使用自定义列表

struct ContentView: View {
    let htmlText = "<p>This is the paragraph</p><p>Add more content here to test height adaptation!</p>"
    
    var body: some View {
        PostListView(htmlText: htmlText, itemCount: 21)
            .background(Color.clear)
    }
}

这两个方案都能解决你遇到的滚动卡顿、内容加载异常的问题,方案二更适合大量数据的场景,性能提升更明显。

内容的提问来源于stack exchange,提问作者exitoffline

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 19:52:38