[英]Images in UITableViewCell change after scrolling down and back up
[英]UITableViewCell Images Changing after Scrolling Up and Down but TextLabel Text Remain Same (iOS8, Swift)
我正在尝试创建一个RSS应用程序进行练习。 所以我的tableView单元格同时具有textLabel和image。 我的textLabel的文本和图像数据来自存储在Core Data中的词典。 有些单元格有图像,有些则没有。 tableView的初始加载对我来说看起来不错。 但是当我上下滚动时,单元格的图像似乎发生了变化。 单元格的textLabel文本虽然没有改变。
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
self.configureCell(cell, atIndexPath: indexPath)
return cell
}
func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
cell.textLabel!.text = object.valueForKey("title")!.description
var image: UIImage?
if let imageData = object.valueForKey("imageData") as? NSData {
image = UIImage(data: imageData)
let itemSize = CGSizeMake(80, 80)
UIGraphicsBeginImageContext(itemSize)
let imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height)
image?.drawInRect(imageRect)
cell.imageView?.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
}
如果初始tableView正确加载,则意味着我的核心数据正确存储了我的数据映射。 但是,当上下滚动时, configureCell
被再次调用,因为它需要重绘单元格。 cell.textLabel!.text = object.valueForKey("title")!.description
再次正确设置,但此处没有图像。 不知道为什么会这样。 请给一些指针。
我曾经遇到过同样的问题,我认为这与重用单元格未处于默认状态有关,因此有时您设置的图像会被重用。 为了解决这个问题,我只对imageData做了else
条件,如果找不到图像,则将图像设置为默认图像。 我确定您也可以在此处将其设置为nil。
if let image = UIImage(contentsOfFile: imagePath) {
cell.imageView.image = image
} else {
// Default image or nil
cell.imageView.image = UIImage(named: "Calendar")
}
而且我不建议将图像作为原始数据存储在核心数据中,因为这样效率很低。 而是将它们下载到您的文档目录,并将文件名存储在核心数据中。
我所做的是从imageView中删除图像,然后再次设置图像。 这个对我有用。
cell.imageView.image = nil
cell.imageView.image = UIImage(named:"Calendar")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.