Search code examples
iosobjective-cuitableviewuibackgroundcolor

Change specific UICell backgroundcolor


I have a UITableView filled with stuff from a database.

Now I want to change the background color of only one cell, the one that is set 'active item'.

How can I find the cell with (as example) name = "Active Cell" and change the background color of that cell only.

Hope you guys understand, don't know how to explain it.


Solution

  • If you know which is the active item as the table is loaded / reloaded you can use...

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *CellIdentifier = @"Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
        if (!cell)
        {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    
           // permanent cell styling in here.
    
       }
    
        // non-permanent cell styling in here.
    
        // example
        MYCustomDataObject *object = [myDataArray objectAtIndex:indexPath.row]; 
    
        cell.textlabel.text = object.text;
    
        BOOL isActive = [object.text isEqualToString:@"Active Cell"];
        cell.backgroundColor = isActive ? [UIColor redColor]:[UIColor clearColor];
    
        return cell;
    }
    

    If you need to access it at another time... say you've just set a new active item... you should call [myTableView reloadData]; when the active item changes also.