更改UITableView单元格颜色

时间:2015-07-20 19:43:11

标签: ios swift 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()
        }
    }

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

有什么想法吗?

2 个答案:

答案 0 :(得分: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
    }

答案 1 :(得分:0)

您应该更改contentView颜色

cell.contentView.backgroundColor = UIColor.greenColor()

方法cellForRowAtIndexPath对它也有好处