【问题标题】:IOS images in TableView is there any way to improve performanceTableView中的IOS图像有什么方法可以提高性能
【发布时间】:2017-05-02 15:52:25
【问题描述】:

我有一个由 Json 填充的 tableView。返回的字段之一具有它需要下载的图像的完整 URL。我这样做并且一切正常,但是有时当我向下滚动时,您会在 TableView 行中看到错误的图像,然后它会在 2 秒后变回,这发生在我看到大约 12 或 13 张图像之后,然后它开始变慢。我想纠正这一点。我到目前为止的代码是这个。

stream_image_string:它具有图像 URL 的完整路径

var Stream_Cache = NSCache() : 缓存图片

下面的代码在 TableView -> UITableViewCell

再一次,一切都按预期的方式运行,只是想知道我是否可以获得更好的性能。

    // if more than 0 then it has a URL 
   if stream_image_string[indexPath.row].characters.count > 0 {
        if let image = Stream_Cache.object(forKey: stream_image_string[indexPath.row] as AnyObject) as? UIImage {
            cell.stream_image.image = image
        } else {
            if cell.stream_image != nil {
            let strCellImageURL = self.stream_image_string[indexPath.row]
            let imgURL: NSURL = NSURL(string: strCellImageURL)!
        let request:NSURLRequest =  NSURLRequest(url: imgURL as URL)
        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config)
      cell.Stream_Image_Height.constant = 400
        let task = session.dataTask(with: request as URLRequest,    completionHandler: {(data, response, error) in
            DispatchQueue.main.async(execute: { () -> Void in

                if data != nil {
                cell.stream_image.image = UIImage(data: data!)
                } else {
                     cell.Stream_Image_Height.constant = 0
                }


            })
        });

        task.resume()
            }
    }
    } else {

        cell.Stream_Image_Height.constant = 0
    }

【问题讨论】:

    标签: ios swift uitableview swift3


    【解决方案1】:

    您可以将图像设置为占位符(而不是 nil)并使用预取(参见 WWDC'16 session 219)提前开始为您的图像提取:

        protocol UITableViewDataSourcePrefetching {
           func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [NSIndexPath])
    
        optional func tableView(_ tableView: UITableView, cancelPrefetchingForRowsAt indexPaths:
        [NSIndexPath])
    
    }
    

    【讨论】:

      【解决方案2】:

      图片下载应该没问题,你要做的就是实现:

      override func prepareForReuse() {
           stream_image.image = nil
      }
      

      在你的牢房里

      【讨论】:

        猜你喜欢
        • 2012-09-13
        • 1970-01-01
        • 1970-01-01
        • 2010-11-23
        • 2014-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多