【问题标题】:Refresh UITableView in Swift在 Swift 中刷新 UITableView
【发布时间】:2016-02-22 11:09:58
【问题描述】:

我在刷新 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()
    }
}

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

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

self.status = "start"
self.tableView.reloadData()
}

但效果不是很好,因为我必须滚动才能更新背景颜色。

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

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

我哪里错了?

【问题讨论】:

  • 你有 self.currentIndexPath 吗?因为我在 func startAction(sender: AnyObject) 中看不到任何与 self.currentIndexPath 相关的代码
  • 我只是忘记在这里引用它,但它在我的代码中定义得很好。我用 currentIndexPath 更新了上面的代码
  • 请检查您是否分配了tableView IBOutlet。
  • @jay:当然是的。

标签: ios xcode swift uitableview


【解决方案1】:

将您对 reloadData 的调用替换为:

DispatchQueue.main.async { self.tableView.reloadData() }

【讨论】:

  • 这是正确答案。 UI 更新应在 DispatchQueue.main 上运行。
【解决方案2】:

您可能应该将您的逻辑放在cellForRowAtIndexPath 委托方法中,当您重新加载表时,它将被调用。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath:indexPath)
    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()
    }
    return cell
}

由于我看不到您当前对该方法的实现,我只是猜测您对单元格的出队,您可能需要稍微更改一下,如果您可以在您的问题中发布此代码,我可以提供帮助。

【讨论】:

  • 我也尝试按照您所说的在 cellForRowAtIndexPath 中进行操作。但我总是必须在点击“开始”后滚动更新背景颜色
【解决方案3】:

你把逻辑放错地方了。 willDisplayCell 在绘制单元格之前被调用,这就是为什么在滚动时看到变化是有意义的。调用reloadData 将调用cellForRowAtIndexPath,因此您应该将逻辑移至该方法。

【讨论】:

  • 我已经在 cellForRowAtIndexPath 中完成了,但我必须滚动更新单元格。
【解决方案4】:

不要在 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()
}

【讨论】:

  • 没有回答刷新tableview的问题
  • 仍然无法正常工作。我将颜色规则放在“cellForRowAtIndexPath”中,但它不起作用:我必须滚动 tableView 以更新单元格
猜你喜欢
  • 1970-01-01
  • 2014-10-23
  • 1970-01-01
  • 2015-03-28
  • 1970-01-01
  • 2016-05-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多