我正在尝试为练习创建一个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正确加载,则表示我的Core Data正确存储了我的数据映射。但是当向下和向上滚动时,再次调用configureCell
,因为它需要重绘单元格。 cell.textLabel!.text = object.valueForKey("title")!.description
再次正确设置,但不在此处显示。不知道为什么它会像这样。请给出一些指针。
答案 0 :(得分:1)
我曾经遇到过同样的问题,我认为它与重用的单元格没有处于默认状态有关,所以有时你设置的图像会被重用。为了解决这个问题,我在imageData上做了else
条件,如果没有找到图像,则将图像设置为默认图像。我相信你也可以把它设置为零。
if let image = UIImage(contentsOfFile: imagePath) {
cell.imageView.image = image
} else {
// Default image or nil
cell.imageView.image = UIImage(named: "Calendar")
}
我不建议将图像作为原始数据存储在核心数据中,因为这可能非常低效。而是将它们下载到您的文档目录并将文件名存储在核心数据中。
答案 1 :(得分:0)
我所做的是从imageView中删除图像并再次设置图像。它对我有用。
format(as.Date(paste(str1, '01'), "%B %Y %d") , "%Y%m")