在Swift中刷新UITableView

问题描述 投票:4回答:4

我在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来更新背景颜色或一些图像。

我哪里错了?

ios xcode swift uitableview
4个回答
6
投票

将您的调用替换为reloadData:

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

1
投票

您可能应该将您的逻辑放在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
}

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


0
投票

你在错误的地方得到了逻辑。在绘制单元格之前调用willDisplayCell,这就是为什么滚动时看到更改的原因。调用reloadData将调用cellForRowAtIndexPath,因此您应该将逻辑移动到该方法。


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()
}
© www.soinside.com 2019 - 2024. All rights reserved.