簡體   English   中英

UITableViewCell圖像在上下滾動后發生變化,但TextLabel文本保持不變(iOS8,Swift)

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM