首页 > 解决方案 > UITableViewCell 中的 WKWebView 需要一些时间来加载(仅第一个单元格加载)

问题描述

我有一个UITableViewCell包含一个WKWebView(我的目标是显示单元格中的 YouTube 视频)。

这是我尝试过的:

import UIKit; import WebKit

class ViewController: UIViewController {
    var displayCell = false {
        didSet { updateView() }
    }
    
    @IBOutlet weak var tableView: UITableView! {
        didSet { tableView.register(UINib(nibName: "VideoCell", bundle: .main), 
                                          forCellReuseIdentifier: "VideoCell") }
    }
    
    @IBAction func tapped() {
       displayCell.toggle()
       updateView()
    }

    private func updateView() {
        tableView.reloadData()
    }
}

extension ViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "VideoCell", for: indexPath) as! VideoCell
        if let url = URL(string: "https://www.youtube.com/embed/qxWwEPeUuAg") {
            cell.wkWebView.load(URLRequest(url: url))
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        200
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        displayCell ? 1 : 0
    }    
}

final class VideoCell: UITableViewCell {
    @IBOutlet weak var wkWebView: WKWebView!
}

点击按钮隐藏或显示第一个单元格。我意识到显示视频单元时会出现延迟,但只是第一次。我什至没有加载 URL 就试过了,延迟仍然存在。所以我想当WKWebView应用程序第一次缓存单元格时有问题,当单元格出列时不会再发生这种情况。但我找不到什么。

你可以帮帮我吗?非常感谢。

标签: iosuitableviewuikitwkwebview

解决方案


推荐阅读