我想用显示图像的单元格实现一个表视图。图像将异步加载。为了更好地滚动,如果单元格滚动出视图,我希望取消请求。到目前为止,我的代码工作正常,但我不知道如何检测该单元格是可见的还是已经“滚动”了。
这是我的密码:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("EventsTableCell", forIndexPath: indexPath) as! EventsTableCell
var elem : Event = data[indexPath.row] as Event
cell.headlineLabel.text = elem.getName()
cell.secondLabel.text = elem.getDescription()
cell.progressView.setProgress(0.0,animated: true)
if let image = ImageCache.getImage(elem.getId()) {
cell.coverImage.image = image
cell.progressView.removeFromSuperview()
} else {
cell.coverImage.image = UIImage(named: "loading")
if(elem.getCover() == nil){
//NOIMAGE
cell.progressView.removeFromSuperview()
}else{
println("start request for" + elem.getName()!)
cell.request = Alamofire.request(.GET, elem.getCover()!)
.progress {
(_, totalBytesRead, totalBytesExpectedToRead) in
dispatch_async(dispatch_get_main_queue()) {
// 6
cell.progressView.setProgress(Float(totalBytesRead) / Float(totalBytesExpectedToRead), animated: true)
// 7
if totalBytesRead == totalBytesExpectedToRead {
cell.progressView.removeFromSuperview()
}
}
}
.response { (request, response, data, error) in
if error == nil && cell.coverImage.image != nil {
ImageCache.addImage(elem.getId(),image: UIImage(data: data!, scale:1)!)
cell.coverImage.image = UIImage(data: data!, scale:1)
}else{
}
}
}
}
return cell
}使用以下代码,我可以取消请求:
cell.request!.cancel()我还注意到,progressView有时不显示,或者可能会从超级视图中删除到早期,也许有人可以帮忙。
谢谢托拜厄斯
发布于 2015-08-19 13:37:21
由于性能原因,表格视图重用单元格。因此,相同的细胞可以在不同的indexPath中使用大量的时间。
跟随线
tableView.dequeueReusableCellWithIdentifier("EventsTableCell", forIndexPath: indexPath) as! EventsTableCell 只有在没有人可重用的情况下才创建新的EventsTableCell对象!
因此,现在有一个progressView问题是明确的--您可以通过调用
cell.progressView.removeFromSuperview()但你从不加进去。例如,您可以在dequeueReusableCellWithIdentifier调用之后添加它,如果需要,可以稍后删除。我还认为,在您的情况下,最好不要删除/添加它,而是隐藏/显示:
cell.progressView.hidden = false对于图像请求也是如此--您可以调用
cell.request?.cancel()就在dequeueReusableCellWithIdentifier之后
为了使您的代码更加明显,您可以在prepareForReuse方法EventsTableCell中取消,但是它会产生同样的效果。
prepareForReuse 准备一个可重用的单元格,以供表视图的委托重用。
发布于 2015-08-19 13:51:12
为了更好地滚动,如果单元格滚动出视图,我希望取消请求。
实现tableView:didEndDisplayingCell:forRowAtIndexPath:,并在其中取消此行的下载。这正是这个委托方法的作用所在!
https://stackoverflow.com/questions/32096259
复制相似问题