UITableViewCell图像直到选中才会显示

时间:2015-05-04 17:41:31

标签: ios objective-c uitableview swift afnetworking

我的UITableViewCells图像正在显示,直到我向上滚动,直到选中单元格才会显示图像。

当我从另一个ViewController切换到初始ViewController *(包含图像)时,也会出现同样的问题*

我已经检查过图像的imgURL是否正确。

使用的库是:AFNetworking for the image

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("FeedCell", forIndexPath: indexPath) as! MyCell
    cell.itemImageView.image = nil
    self.configureCell(cell, atIndexPath: indexPath)
    return cell
}

// AFNetworking download and display image
func uploadIMG(cell:MyCell,imgURL:NSURL,placeholderIMG:String,atIndexPath indexPath: NSIndexPath) {

    var imageRequest: NSURLRequest = NSURLRequest(URL: imgURL)
    cell.itemImageView!.setImageWithURLRequest(imageRequest, placeholderImage: UIImage(contentsOfFile: "logo.png"), success: { [weak cell] request,response,image in

        if (cell != nil) {
            cell!.itemImageView.image = image
        }}        
        , failure: nil)
}

// called from cellForRowAtIndexPath, retrieve img url to update image
func configureCell(cell: MyCell, atIndexPath indexPath: NSIndexPath) {
    let item = self.items[indexPath.row] as MWFeedItem
    var URLofImage: NSURL = NSURL(string: item.link)!
    var session = NSURLSession.sharedSession()
    let task = session.dataTaskWithURL(URLofImage, completionHandler: {(data,response, error) in
        let text = NSString(data: data, encoding: NSUTF8StringEncoding)
        var home = HTMLDocument(data: data, contentTypeHeader: text as! String)
        var div = home.nodesMatchingSelector("img")
        var urlString = div[1].firstNodeMatchingSelector("img")
        let urlData = (urlString as HTMLElement).firstNodeMatchingSelector("img")
        var urlFinal = urlData.attributes["src"]! as! String

        if urlFinal != "/images/system/bookmark-shorturl.png" {
            // call updateIMG function
            self.uploadIMG(cell, imgURL: NSURL(string: "http:www.animenewsnetwork.com" + urlFinal)!, placeholderIMG: "logo.png",atIndexPath: indexPath)
        }
    })

问题的图像表示(初始图像正常工作)

Initial Image (Working fine)

第二张图片(我向下滚动,然后向上滚动,图片不显示)

enter image description here

我选择了一些细胞,然后会显示这些细胞的图像

enter image description here

4 个答案:

答案 0 :(得分:2)

尝试将图像设置为单元格后,通过调用方法tableView:reloadRowsAtIndexPaths:withRowAnimation在表格视图中更新该单元格。或者使用自定义图像视图编写自定义单元格。请不要忘记图像设置代码必须在主线程中运行。

答案 1 :(得分:2)

问题是我的图像没有在主线程上设置。为了解决这个问题,我只使用下面的代码,确保我的图像能够立即设置。

dispatch_async(dispatch_get_main_queue(), {
 // do image functions here

)}

答案 2 :(得分:0)

误读了问题,但保留此问题以防万一有人遇到类似问题,但使用自动布局。

我相信您正在使用自动布局。因此,如果imageView的帧大小使用内在内容大小(它的图像大小),那么当没有图像时它将是CGSizeZero。首次显示单元格时没有图像,因为需要下载它。然后下载图像并将其分配给imageView.image。这不会自动使布局无效。您需要这样做,以便根据图像的大小重新计算imageView框架。滚动并向后滚动或选择它后显示的原因是因为图像已在该时间内下载,并且在再次显示或选择时单元格布局会重新计算。

下面是我的TestCell和TestViewController

import UIKit
import AFNetworking

class TestCell : UITableViewCell {
    static let cellIdentifier = "TestCell"

    @IBOutlet var downloadedImageView: UIImageView!
    @IBOutlet var rowLabel: UILabel!
    @IBOutlet var statusLabel: UILabel!

}


class TestTableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        tableView.rowHeight = 100
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 30;
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier(TestCell.cellIdentifier, forIndexPath: indexPath) as! TestCell

        let randomName = "\(Random.firstName().lowercaseString).\(Random.lastName().lowercaseString)"
        let randomImageURL = NSURL(string: Random.avatarImageURL(name: randomName))!

        cell.rowLabel.text = String(indexPath.row)
        cell.statusLabel.text = "Not Downloaded"

        var imageRequest: NSURLRequest = NSURLRequest(URL: randomImageURL)
        cell.downloadedImageView.setImageWithURLRequest(imageRequest, placeholderImage: UIImage(named: "placeholder.png"),
            success: { [weak cell]
                (request, response, image) in
                if let cell = cell {
                    cell.downloadedImageView.image = image
                    cell.rowLabel.text = String(indexPath.row)
                    cell.statusLabel.text = "Downloaded"
                }
            },
            failure: { [weak cell]
                (request, response, error) in
                if let cell = cell {
                    cell.downloadedImageView.image = nil
                    cell.rowLabel.text = String(indexPath.row)
                    cell.statusLabel.text = "Failed: \(error.localizedDescription)"
                }
            })

        return cell

    }



}

//
//  Random.swift

import Foundation


class Random {


    static let firstNames = ["Tora", "Shasta", "Camelia", "Gertrudis", "Charita", "Donita", "Debbra", "Shaquana", "Tommy", "Shara", "Ignacia", "Cassondra", "Melynda", "Lisette", "Herman", "Rhoda", "Farah", "Tim", "Tonette", "Johnathon", "Debroah", "Britni", "Charolette", "Kyoko", "Eura", "Nevada", "Lasandra", "Alpha", "Mirella", "Kristel", "Yolande", "Nelle", "Kiley", "Liberty", "Jettie", "Zoe", "Isobel", "Sheryl", "Emerita", "Hildegarde", "Launa", "Tanesha", "Pearlie", "Julianna", "Toi", "Terina", "Collin", "Shamika", "Suzette", "Tad"]

    static let lastNames = ["Austen", "Kenton", "Blomker", "Demars", "Bibbs", "Eoff", "Alcantara", "Swade", "Klinefelter", "Riese", "Smades", "Fryson", "Altobelli", "Deleeuw", "Beckner", "Valone", "Tarbox", "Shumate", "Tabone", "Kellam", "Dibiase", "Fasick", "Curington", "Holbrook", "Sulzer", "Bearden", "Siren", "Kennedy", "Dulak", "Segers", "Roark", "Mauck", "Horsman", "Montreuil", "Leyva", "Veltz", "Roldan", "Denlinger", "James", "Oriley", "Cistrunk", "Rhodes", "Mcginness", "Gallop", "Constantine", "Niece", "Sabine", "Vegter", "Sarnicola", "Towler"]


    class func int(#min: Int, max: Int) -> Int {
        return Int(arc4random_uniform(UInt32(max-min))) + min //???: RTFM on arc4random, might be need (max+1)-min.
    }

    class func int(#range: Range<Int>) -> Int {
        return int(min: range.startIndex, max: range.endIndex)
    }

    class func selectElement<T>(#array: [T]) -> T {
        return array[int(range: 0..<array.count)]
    }


    class func firstName() -> String {
        return Random.selectElement(array: Random.firstNames)
    }

    class func lastName() -> String {
        return Random.selectElement(array: Random.lastNames)
    }

    class func avatarImageURL(var name: String? = nil) -> String {

        if name == nil {
            name = "(Random.firstName().lowercaseString).Random.lastName().lowercaseString"
        }

        let avatarImageSize = Random.int(min: 40, max: 285)
        return "http://api.adorable.io/avatars/\(avatarImageSize)/\(name!)@gmail.png"
    }


    class func imageURL() -> String {

        let imageWidth = Random.int(min:120, max:1080)
        let imageHeight = Random.int(min:120, max:1080)

        return "http://lorempixel.com/g/\(imageWidth)/\(imageHeight)/"
    }

}

答案 3 :(得分:0)

滚动时,单元格将重新加载。 (您重新加载以重新下载图像) - &gt;它的问题。

解决: 您可以在下载后为保存图像数据创建阵列。

并且单元格从此数组中获取图像,而不是重新下载

希望这有用!