如何为选定的单元格设置不同的颜色以及为什么会崩溃?

时间:2016-06-22 01:48:46

标签: ios swift uitableview

我可以在选择单元格时更改颜色,但是当我单击另一个单元格时,我需要先前的单元格在选择之前转到原始颜色。当我选择一个单元格并向下滚动所选单元格不可见的位置并单击另一个单元格时出现错误。请看下面的错误。

 func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let cell: selectcell = table.cellForRowAtIndexPath(indexPath) as! selectcell
    cell.viewcheck.backgroundColor = UIColor.blackColor()
}

func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    let cell: selectcell = table.cellForRowAtIndexPath(indexPath) as! selectcell // fatal error: unexpectedly found nil while unwrapping an Optional value
    cell.viewcheck.backgroundColor = UIColor.whiteColor()
}

2 个答案:

答案 0 :(得分:0)

您可以考虑在selectedBackgroundView课程上尝试UITableViewCell属性。您可以在cellForRowAtIndexPath中执行以下操作,在选择时将整个单元格设置为特定颜色:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
   let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! selectcell
   let background = UIView(frame: cell.frame)
   background.backgroundColor = UIColor.blackColor()
   cell.selectedBackgroundView = background

   return cell
}

如果您有任何疑问,请询问!

答案 1 :(得分:0)

试试这个,虽然最终它听起来像你的数据源(无论是数组还是其他)都无法正常工作。

func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        let cell = tableView.cellForRowAtIndexPath(indexPath) as! selectcell
        cell.cardView.backgroundColor = UIColor.blackColor()
        return true
    }

func tableView(tableView: UITableView, didHighlightRowAtIndexPath indexPath: NSIndexPath) {
    let cell = tableView.cellForRowAtIndexPath(indexPath) as! selectcell
    cell.cardView.backgroundColor = UIColor.blackColor()
}

func tableView(tableView: UITableView, didUnhighlightRowAtIndexPath indexPath: NSIndexPath) {
    let cell = tableView.cellForRowAtIndexPath(indexPath) as! selectcell
    cell.cardView.backgroundColor = UIColor.whiteColor()
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let cell = tableView.cellForRowAtIndexPath(indexPath) as! selectcell
    cell.cardView.backgroundColor = UIColor.blackColor()
}

func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    let cell = tableView.cellForRowAtIndexPath(indexPath) as! selectcell
    cell.cardView.backgroundColor = UIColor.whiteColor()
}

func tableView(tableView: UITableView, willDeselectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
    let cell = tableView.cellForRowAtIndexPath(indexPath) as! selectcell
    cell.cardView.backgroundColor = UIColor.whiteColor()
    return indexPath
}