Tableview首先重用单元格并显示错误数据

Sly*_*oth 2 xcode ios swift

你好,我一直有这个问题.我想阻止tableview重用单元格.当我滚动时它会一直显示错误信息然后显示正确的事情,如几毫秒.如何阻止tableview重用单元格或如何重用单元格并使其不这样做.

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return cats.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cellIdentifier = "CategoryTableViewCell"
    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! CategoryTableViewCell
    cell.nameLabel.text = cats[indexPath.row].categoryName
    cell.subNameLabel.text = cats[indexPath.row].appShortDesc
    let catImageUrl = cats[indexPath.row].imageUrl
            let url = NSURL(string: "https:\(catImageUrl)")
            let urlRequest = NSURLRequest(URL: url!)
            NSURLConnection.sendAsynchronousRequest(urlRequest, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in
                if error != nil {
                    print(error)
                } else {
                    if let ass = UIImage(data: data!) {
                            cell.photoImageView.image = ass
                        }
                    self.loading.stopAnimating()
                }
            }
    return cell
}
Run Code Online (Sandbox Code Playgroud)

vac*_*ama 11

问题是您正在看到前一个单元格中的图像.只需在nil将重用的单元格出列时将图像初始化为:

cell.photoImageView.image = nil
Run Code Online (Sandbox Code Playgroud)

或将其设置为您选择的默认图像.


请注意,加载后更新图像的方式存在问题.

  1. 当图像最终加载时,该行可能不再在屏幕上,因此您将更新已经重用的单元格.

  2. 更新应该在主线程上完成.

更好的方法是使用一个缓存单元格图像的数组.将图像加载到数组中,然后告诉tableView重新加载该行.

像这样的东西:

dispatch_async(dispatch_get_main_queue()) {
    self.imageCache[row] = ass
    self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: row, inSection: 0)],
        withRowAnimation: .None)
}
Run Code Online (Sandbox Code Playgroud)