ChallengerGuy
ChallengerGuy

Reputation: 2395

Swift 2 colored background of UITableViewCell at certain indexPath.rows

I have an iOS Xcode 7.3 project written in Swift 2. I have a UITableView that contains an array of information of type [String] called details. When the user clicks on one of the UITableViewCells, it segues them to another ViewController where they can enter notes for that selected detail. Afterwards they can segue back to the UITableView. My goal is if a detail in the UITableView has a note attached that was typed, that cell's backgroundColor would be yellow.

Below is:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    // Transfer details of selected cell to notes view
    var selectedCell = details[indexPath.row]
    detailsTransfer = selectedCell // Transfer detail information
    detailLocation = indexPath.row // Transfer detail location in array

}

This transfers the details and location in the array for adding notes to the detail. I then save the detailLocation to a new array of type Int. I'm thinking to get the color change in the cell background, I'd need to loop through the [Int] and only those cells in the UITableView would have a backgroundColor of yellowColor()? I don't know if this is correct and/or how/where this code would go. Maybe the loop in: tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! ?? Can someone please help? Thank you.

UPDATE

My cellForRowAtIndexPath is:

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {

    let cellIdentifier = "LogTableViewCell"

    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! LogTableViewCell

    cell.logLabel?.text = details[indexPath.row]

    return cell
}

Still trying to compare indexPath.row for color change.

Upvotes: 0

Views: 573

Answers (1)

Moshe
Moshe

Reputation: 58067

In the main table view, tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! method, you can do something like this:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell! {

    // Transfer details of selected cell to notes view
    var selectedCell = details[indexPath.row]
    detailsTransfer = selectedCell // Transfer detail information
    detailLocation = indexPath.row // Transfer detail location in array

    if selectedCell.hasNote {

      cell.backgroundColor = UIColor.yellowColor()
   } 
}

You don't need to loop because the table view data source already checks each row for you.

Upvotes: 1

Related Questions