在Swift中刷新UITableView

Joj*_*ojo 5 xcode uitableview ios swift

我在刷新UIViewController内的自定义UITableView时遇到问题。

当出现时,tableView的所有单元格都有清晰的背景色。我上面有一个“开始”按钮,当我单击它时,我希望所有单元格都具有另一种颜色。

我在以下位置指定了规则:

    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {

    if self.status == "start" {

        if indexPath != self.currentIndexPath {
            cell.backgroundColor = UIColor(red: 0  , green: 0, blue: 0, alpha: 0.5)
        } else {
            cell.backgroundColor = UIColor.clearColor()
        }

    } else {
        cell.backgroundColor = UIColor.clearColor()
    }
}
Run Code Online (Sandbox Code Playgroud)

在“开始”操作按钮中,我调用: self.tableView.reloadData

@IBAction func startAction(sender: AnyObject) {
self.currentIndexPath = NSIndexPath(forRow: 0, inSection: 0)

self.status = "start"
self.tableView.reloadData()
}
Run Code Online (Sandbox Code Playgroud)

但这不能很好地工作,因为我必须滚动以更新背景色。

我尝试使用该self.tableView.reloadRowsAtIndexPaths方法。但是结果是一样的。

我总是必须滚动tableView来更新背景色或某些图像。

我哪里错了?

小智 8

将对reloadData的调用替换为:

DispatchQueue.main.async { self.tableView.reloadData() }
Run Code Online (Sandbox Code Playgroud)


Res*_*der 0

不要在 WillDisplayCell 上添加代码,而是在 cellForRowAtIndexPath 中添加代码

@IBAction func startAction(sender: UIButton)
{

    let buttonPosition : CGPoint = sender.convertPoint(CGPointZero, toView: self.tableview )

    self.currentIndexPath  = self.tableview.indexPathForRowAtPoint(buttonPosition)!
    self.status = "start"
    self.tableView.reloadData()
}
Run Code Online (Sandbox Code Playgroud)