我有一份Reddit帖子列表,如果存在缩略图,我想要显示它。我已经实现了这个功能,但是它非常不稳定。主要存在两个问题:
- 图片在点击时会被重新调整大小
- 图片在滚动时会乱跳
这是代码:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Post", forIndexPath: indexPath) as UITableViewCell
let post = swarm.posts[indexPath.row]
cell.textLabel!.text = post.title
if(post.thumb? != nil && post.thumb! != "self") {
cell.imageView!.image = UIImage(named: "first.imageset")
var image = self.imageCache[post.thumb!]
if(image == nil) {
FetchAsync(url: post.thumb!) { data in // code is at bottom, this just drys things up
if(data? != nil) {
image = UIImage(data: data!)
self.imageCache[post.thumb!] = image
dispatch_async(dispatch_get_main_queue(), {
if let originalCell = tableView.cellForRowAtIndexPath(indexPath) {
originalCell.imageView?.image = image
originalCell.imageView?.frame = CGRectMake(5,5,35,35)
}
})
}
}
} else {
dispatch_async(dispatch_get_main_queue(), {
if let originalCell = tableView.cellForRowAtIndexPath(indexPath) {
originalCell.imageView?.image = image
originalCell.imageView?.frame = CGRectMake(5,5,35,35)
}
})
}
}
return cell
}
这是应用程序加载时的样子,看起来一切都正常:
**图片和标题来自reddit,不是由我生成的**
承诺的FetchAsync类编辑:
class FetchAsync {
var url: String
var callback: (NSData?) -> ()
init(url: String, callback: (NSData?) -> ()) {
self.url = url
self.callback = callback
self.fetch()
}
func fetch() {
var imageRequest: NSURLRequest = NSURLRequest(URL: NSURL(string: self.url)!)
NSURLConnection.sendAsynchronousRequest(imageRequest,
queue: NSOperationQueue.mainQueue(),
completionHandler: { response, data, error in
if(error == nil) {
self.callback(data)
} else {
self.callback(nil)
}
})
callback(nil)
}
}
originalCell
常量是单元格的旧值,因为你从tableView.cellForRowAtIndexPath(indexPath)
获取它,并且你正在“刷新”它的函数中。所以尝试在cell
上进行更改。 - PintouchoriginalCell
切换为cell
并没有解决任何问题,如果有的话,似乎会使错误更加严重,但这可能只是我的想象。 - cadlactableView.reloadData
。(我现在无法测试,所以这只是一个建议) - Pintouch