2015-07-20 75 views
0

我有以下代码:变化的UITableView单元格颜色

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { 
     if (self.from! == "Hello") { 
      println("Hello") 
      cell.backgroundColor = UIColor.redColor() 
      cell.textLabel?.textColor = UIColor.yellowColor() 
     } else { 
      println("Not Hello") 
      cell.backgroundColor = UIColor.yellowColor() 
      cell.textLabel?.textColor = UIColor.redColor() 
     } 
    } 

的问题是,它适用于整个表 - 我只是想改变创建的最后一个单元格。

有什么想法?

+0

什么是你的表中的数据源?数组? – Shades

回答

0

你应该改变内容查看颜色

cell.contentView.backgroundColor = UIColor.greenColor() 

方法cellForRowAtIndexPath也不错吧

+0

谢谢 - 我也可以用它来改变当前单元格的cell.textLabel?.textColor = UIColor.yellowColor()。 ContentView不支持textColor :( – New2JQ

+0

标签,你可以改变cell.label等......但背景它是conteView属性。如果你想改变最后一个单元格取你tableview的最后indexPath索引。但是意识到如果你的tableview是可重用的,最后一个单元格会总是变化 – Anton

+0

我将cell.contentView.backgroundColor = UIColor.redColor()添加到了willDisplayCell函数,但它仍然更新整个表格,而不仅仅是一个单元格 – New2JQ

1

您需要确定多少行是在你的表,并应用了颜色变化,只是该行。我看到您正在尝试更改willdisplaycell中的颜色。如果您愿意,您可以在创建单元格时执行此操作。我假设你正在使用可重用的单元格。你知道有多少行,在你的部分,因为这是在

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return myData.count 
    } 

创建单元格时设置,则:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("MyCell") as! UITableViewCell 
    cell.textLabel?.text = myData[indexPath.row] 
    if (indexPath.row == myData.count-1) { 
     cell.backgroundColor = UIColor.yellowColor() 
     return cell 
    } 
相关问题