binsnoel
binsnoel

Reputation: 276

UITableView Static cells - Selection color not working

I have a problem regarding my static cells. This is my tableview structure:
https://i.sstatic.net/1gq1y.png (I cant post images)

The cell background color is Gray and the contentView background color is ClearColor. The cell is not using a custom UITableViewCell subclass.

I set the Selection to Blue in the storyboad. However, when I run it, the output is Gray

I tried doing it manually in the didSelectRowAtIndexPath with this code:

currentCell.contentView.backgroundColor = self.view.tintColor;

but it turns out like this: https://i.sstatic.net/Zfatl.png

The Label in the Cell doesn't change to white and the Accessory background isn't changing. Please help. Thank you so much!

Upvotes: 1

Views: 2188

Answers (4)

Michał Ziobro
Michał Ziobro

Reputation: 11752

I am doing this selection this way. I have static header cells as 0-index rows in tableview's sections

 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        print("Did select row \(indexPath.row) in section \(indexPath.section)")

        if indexPath.row > 0 {
            let cell = tableView.cellForRow(at: indexPath)
            cell?.selectionStyle = .gray
        }
    }

Upvotes: 1

binsnoel
binsnoel

Reputation: 276

Note that in iOS 7, using

[cell setSelectionStyle:UITableViewCellSelectionStyleBlue];

will not work as expected, because in iOS 7 this is now gray, even if you pass the constant above. See:

https://developer.apple.com/library/ios/documentation/uikit/reference/UITableViewCell_Class/Reference/Reference.html#//apple_ref/c/tdef/UITableViewCellSelectionStyle

Vern Jensen's answer: https://stackoverflow.com/a/19257253/2575115

Upvotes: 0

Tapansinh Solanki
Tapansinh Solanki

Reputation: 194

Add the following code to your TableView: cellForRowAtIndexPath method.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

 // Write code for create your cell and properties regarding that cell
 //add this line 
   cell.selectionStyle = UITableViewCellSelectionStyleDefault;
    UIView *bgColorView = [[UIView alloc] init];
    bgColorView.backgroundColor = [UIColor blueColor];
    [cell setSelectedBackgroundView:bgColorView];

 return cell;
}

Upvotes: 0

Kavita
Kavita

Reputation: 176

add cell selection stylecolor as stylenone in cellForRowAtIndexPath method.

cell.selectionStyle = UITableViewCellSelectionStyleNone;  



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

 // Write code for create your cell and properties regarding that cell
 //add this line 
 cell.selectionStyle = UITableViewCellSelectionStyleNone; 
 return cell;
}

Upvotes: 0

Related Questions