使用图像冻结tableview中的滚动

时间:2018-03-05 18:35:52

标签: swift uitableview tableview

使用下载网址中的图片冻结桌面视图中的滚动条。

从互联网上下载图片。很好。但是当向下滚动时。

class WebcamViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating {
@IBOutlet var tableView: UITableView!
var images: UIImage!
let searchController = UISearchController(searchResultsController: nil)
var fmoscow: [(name: String, URLs:String, img:String)] = []
var moscow: [(name: String, URLs:String, img:String)] = [
    ("North from the 9th floor of Millikan", "http://131.215.225.22/milcam-north/","1"),
    ("South from the 9th floor of Millikan", "http://131.215.225.22/milcam-south/","2"),
    ("Mount Wilson Observatory", "http://obs.astro.ucla.edu/images/towercam.jpg","3"),
    ("Pine Mountain Club - Mt. Pinos", "http://www.frazmtn.com/mount_abel_cam/mtabelcam.jpg","4"),
    ("Yosemite Half Dome", "https://pixelcaster.com/yosemite/webcams/ahwahnee2.jpg","6"),
    ("Yosemite High Sierra", "https://pixelcaster.com/yosemite/webcams/sentinel.jpg","7"),
    ("Yosemite El Capitan", "https://pixelcaster.com/yosemite/webcams/turtleback.jpg","8"),]


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell: WebcamTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "WebcamTableViewCell") as! WebcamTableViewCell
    cell.wcName.text = self.fmoscow[indexPath.row].name


    DispatchQueue.global(qos: .userInitiated).async {
        DispatchQueue.main.sync() {
            let link = self.fmoscow[indexPath.row].URLs
            let url = NSURL(string:link)
            let data = NSData(contentsOf: url! as URL)
            //self.images = UIImage(data: data! as Data)
            cell.wcImage.image = UIImage(data: data! as Data)
        }
    }
}

2 个答案:

答案 0 :(得分:1)

这很可能是因为您在主线程上下载了图像。

尝试将图像的下载和处理移至后台线程:

DispatchQueue.global(qos: .userInitiated).async {

    let link = self.fmoscow[indexPath.row].URLs

    guard
        let url = URL(string: link),
        let data = try? Data(contentsOf: url),
        let image = UIImage(data: data)
    else {
        return
    }

    DispatchQueue.main.async {
        cell.wcImage.image = image
    }
}

答案 1 :(得分:0)

尝试获取所需的所有数据非常困难。您需要在启动时获取数据。

main