我在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来更新背景颜色或一些图像。
我哪里错了?
将您的调用替换为reloadData:
DispatchQueue.main.async { self.tableView.reloadData() }
您可能应该将您的逻辑放在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
}
由于我无法看到您当前对此方法的实现,我刚刚猜到了您的单元格出列,您可能需要稍微更改一下,如果您可以在您的问题中发布此代码,我可以提供帮助。
你在错误的地方得到了逻辑。在绘制单元格之前调用willDisplayCell
,这就是为什么滚动时看到更改的原因。调用reloadData
将调用cellForRowAtIndexPath
,因此您应该将逻辑移动到该方法。
而不是在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()
}