【发布时间】: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