我正在创建一个小应用程序,用于在 Flickr 的 TableView 中显示图像。该应用程序运行良好,但我在滚动表格 View 时遇到问题,我的表格 View 滞后很多。我认为问题可能出在 GCD 或 Threads 上,我是网络和 GCD 的新手,这是我从 Flickr API 获取图像的代码。
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = flickrTableView.dequeueReusableCellWithIdentifier("cell") as! FlickerTableCell
let flickr = flickrArray[indexPath.row]
dispatch_async(dispatch_get_main_queue(), {
cell.imageViewFlickr.image = flickr.getFlickrImage()
})
cell.labelFlickrTitle.text = flickr.title
return cell
}
//从flickr获取图片的函数
func getFlickrImage()->UIImage{
let imageURL = NSURL(string: "https://farm\(farm).staticflickr.com/\(server)/\(photoId)_\(secret)_m.jpg")!
var flickrImage = UIImage()
if let imageData = NSData(contentsOfURL: imageURL) {
flickrImage = UIImage(data: imageData)!
} else {
print("Image does not exist at \(imageURL)")
}
return flickrImage
}
最佳答案
您从网络获取图像的方法是 getFlickrImage() 是同步方法,因此表格单元等待其响应,并且由于网络调用在主线程中,它会卡住或滞后 UI。您可以将网络调用包装在异步方法中,并使用完成处理程序在主线程中更新 UI,例如:
func getFlickrImage(completion:UIImage ->()){
let imageURL = NSURL(string: "https://farm\(farm).staticflickr.com/\(server)/\(photoId)_\(secret)_m.jpg")!
var flickrImage = UIImage()
let download = dispatch_queue_create("download", nil)
dispatch_async(download) {
if let imageData = NSData(contentsOfURL: imageURL) {
dispatch_async(dispatch_get_main_queue(), {
flickrImage = UIImage(data: imageData)!
completion(flickrImage)
})
} else {
print("Image does not exist at \(imageURL)")
completion(flickrImage)
}
}
}
你的 cellForRowAtIndexPath 会像这样:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = flickrTableView.dequeueReusableCellWithIdentifier("cell") as! FlickerTableCell
let flickr = flickrArray[indexPath.row]
flickr.getFlickrImage { (photo) in
dispatch_async(dispatch_get_main_queue(), {
cell.imageViewFlickr.image = photo
})
}
cell.labelFlickrTitle.text = flickr.title
return cell
}
关于ios - 显示来自网络的图像时 TableView 滞后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41073113/