简体   繁体   中英

Change UITableView Cell Color

I have the following code:

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()
        }
    }

The issue is it's applying to entire table - I just want to change the last cell created.

Any idea?

You need to determine how many rows are in your table and apply the color change to just that row. I see that you are trying to change the color in willdisplaycell. You can do this when you create the cell if you'd like. I assume you are using reusable cells. You know how many rows are in your section because this is set in

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

Then when creating the cell :

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
    }

You should change contentView color

cell.contentView.backgroundColor = UIColor.greenColor()

method cellForRowAtIndexPath also good for it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM