简体   繁体   中英

change the color of the cell when it is tapped in UITableView

I am using UITableView in my application and I have created custom cell in the file DealsCC.xib and when cell is tapped the color of the cell should be changed to blue but it does not happen in my code. I write the code as follows:

static NSString *MyIdentifier = @"dealsCC";
    dealsCC *cell = (dealsCC *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    [cell selectionStyle:UITableViewCellSelectionStyleBlue];

I want to mention that in the line

[cell selectionStyle:UITableViewCellSelectionStyleBlue];

warning msg exists and it is "dealsCC may not respond to -selectionStyle"

plz help me to solve this problem thanx in advance.

请参阅以下链接计算器,请检查您是否遵循correclty他们1) 链接1 2) 链接2 3) 输入链接的描述在这里

Try this in your custom class for the table view cell

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
       self.selectionStyle = UITableViewCellSelectionStyleBlue;
       [super setSelected:selected animated:animated];

}

The warning is because the method should be

[cell setSelectionStyle:UITableViewCellSelectionStyleBlue];

and not [cell selectionStyle:UITableViewCellSelectionStyleBlue];

Use cell.selectionStyle = UITableViewCellSelectionStyleGray; for changing the style of the cell selection. But here the selectionStyle only takes input of UITableViewCellSelectionStyle type.

For changing Color you need to use Image. Use selectedBackgroundView.image property and Follow the tutorial Link

Or you can also try

    cell.selectedBackgroundView = [[[UIView alloc] initWithFrame:CGRectZero] autorelease];
    cell.selectedBackgroundView.backgroundColor = [UIColor redColor];

EDIT:

OK I am updating code in case you have any other controls on the cell, then you can try below code.

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     static NSString *CellIdentifier = @"myCellId";
     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
     if (cell == nil) {
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
     UIView *v = [[[UIView alloc] init] autorelease];
     v.backgroundColor = [UIColor redColor]; // any color of your choice.
     cell.selectedBackgroundView = v;
      // After this line add all other controlls you are adding...
     }
// Set up the cell...
cell.textLabel.text = @"foo";
return cell;
}

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