【问题标题】:Update UITableview cell with new loaded content while scrolling滚动时使用新加载的内容更新 UITableview 单元格
【发布时间】:2016-07-21 03:21:50
【问题描述】:

我有一个UITableView,我使用cellForRowAtIndexPath: 函数下载特定单元格的图像。图像下载是异步执行的,并在很短的时间后完成,并在完成后调用完成块。我将单元格内容设置为完成块内的下载图像,但直到用户完成滚动后它才会更新。我知道原因是因为代码应该在NSRunLoopCommonModes 中运行,但在这种情况下我不知道该怎么做,感谢任何帮助。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{

let dequeued  = self.tableView.dequeueReusableCellWithIdentifier(imageFileCellIdentifier)
        let cell = dequeued as! ImageTableViewCell

    source.FetchImage(imageLocation, completion: { (image) in
        dispatch_async(dispatch_get_main_queue(), { 
            cell.previewImage.image = image
            cell.previewImage.contentMode = .ScaleAspectFill
        }
    })
}

【问题讨论】:

  • 源变量是什么类型?
  • UI 必须在主线程中更新 - 使用 - dispatch_async(dispatch_get_main_queue(), { } 来更新 UI
  • @RJE ,已经有人指出了,我知道我必须在主线程上,我是,这不是这里的问题。
  • @David 它是一个自定义类,可以使用 SD 卡从自定义外部附件加载图像。

标签: swift xcode uitableview nsrunloop


【解决方案1】:

试试这个

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{

let dequeued  = self.tableView.dequeueReusableCellWithIdentifier(imageFileCellIdentifier)
        let cell = dequeued as! ImageTableViewCell

    source.FetchImage(imageLocation, completion: { (image) in

        dispatch_async(dispatch_get_main_queue(), { () -> Void in
             cell.previewImage.image = image
             cell.previewImage.contentMode = .ScaleAspectFill
        })


    })
}

【讨论】:

  • 对不起,这并不能解决问题,代码已经在主队列上运行,但我需要它在 NSRunloopCommonModes 中
【解决方案2】:

UI 必须在主线程中更新

你可以使用这样的东西来更新 imageView - 因为异步完成块可能不会在主线程中调用。

dispatch_async(dispatch_get_main_queue(), {
    cell.previewImage.image = image
    cell.previewImage.contentMode = .ScaleAspectFill
} 

更新用户界面

如果您检查您正在更新的单元格是正确的单元格,那会更好。因为当下载完成(异步)时,单元格可能会滚动出视图,并且该单元格可能会分配给另一行。在这种情况下,您将图像设置到错误的单元格。

例如。

if cell.imageName == 'downloaded_image_name' {
    // do update
}

【讨论】:

  • 已经有人指出了,我知道我必须在主线程上,我是,这不是这里的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-03
  • 1970-01-01
  • 2018-06-16
  • 1970-01-01
相关资源
最近更新 更多