ios - 显示来自网络的图像时 TableView 滞后

标签 ios swift uitableview

我正在创建一个小应用程序,用于在 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/

相关文章:

ios - 同一设备中的不同 UUID。

ios - 如何解析相同key、不同数据的JSON数据?

ios - UITableView:突出显示最后一个单元格,但其他单元格也会突出显示

iphone - 如何根据 tableviewcell 选择将 subview 的 nsdictionary 保存到主视图

ios - 在选项卡栏中第二次打开 View Controller 时大标题崩溃应用程序

ios - Xcode 8 SpriteKit : GameScene. swift 文件未被识别/运行

ios - URLSessionUploadTask 立即自动取消

ios - 在回调中获取所有 UIGestureRecognizer 事件?

swift - 扩展与 LocationPermission 类

objective-c - 显示设备上的可用物理内存(iphone/ipad)