Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to exclude UITableViewCell's subview from changing background when I selected it

I want to exclude UITableViewCell's subview(viewz) from changing background when I selected it.

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;

UIView *viewz = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
viewz.backgroundColor = [UIColor redColor];
[cell.contentView addSubview:viewz];

Cell didn't selected. Everything all right.

http://img32.imageshack.us/img32/1599/screenshot20121129at123.png

Cell has changed color to blue. It's ok. But I do not want that my viewz changing background color to blue. How can I do this?

enter image description here

like image 313
Voloda2 Avatar asked Feb 19 '23 08:02

Voloda2


2 Answers

Add an empty implementation of the setSelected:animated: method to your UITableViewCell subclass

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {

}
like image 139
samvermette Avatar answered Feb 20 '23 21:02

samvermette


It seems you need to touch the background color or the default cell implementation will change it for you. If you add a colored border you'll see viewz is still there, even if you comment the line where I change the background color:

#define VIEWZ_TAG 1234

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ... 
    UIView *viewz = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    viewz.backgroundColor = [UIColor redColor];
    viewz.tag = VIEWZ_TAG;
    viewz.layer.borderWidth = 1;
    viewz.layer.borderColor = [UIColor whiteColor].CGColor;
    [cell.contentView addSubview:viewz];
    ...
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if ([cell isSelected]) {
        UIView *viewz = [cell viewWithTag:VIEWZ_TAG];
        viewz.backgroundColor = [UIColor greenColor];
    }
}

If you want fine control of the cell when it's selected you can use a custom UITableViewCell.

like image 28
djromero Avatar answered Feb 20 '23 20:02

djromero