For too long I struggled with this and resorted to creating a custom image with an accessory. But I found this solution that works well and does not require a special image. The trick is to change the color of the backgroundView element, not the backgroundColor.
UIView *myView = [[UIView alloc] init]; if (indexPath.row % 2) { myView.backgroundColor = [UIColor whiteColor]; } else { myView.backgroundColor = [UIColor blackColor]; } cell.backgroundView = myView;
No need to change the background colors of the accessory or contentView. They will automatically follow.
Note for 2014. Very often you use using - (void) setSelected: (BOOL) selected animated: (BOOL) animated
So, you would have your own class of cells, and you would set the colors for normal / selected like this ...
HappyCell.h @interface HappyCell : UITableViewCell @property (strong, nonatomic) IBOutlet UILabel *mainLabel; etc... @end HappyCell.m @implementation HappyCell -(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; if (self) { } return self; } -(void)awakeFromNib { } - (void)setSelected:(BOOL)selected animated:(BOOL)animated { [super setSelected:selected animated:animated]; if(selected) { self.backgroundColor = [UIColor redColor]; .. other setup for selected cell } else { self.backgroundColor = [UIColor yellowColor]; .. other setup for normal unselected cell } } @end // to help beginners....... // in your table view class, you'd be doing this... -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return yourDataArray.count; } -(UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSInteger thisRow = indexPath.row; ContentsCell *cell = [tv dequeueReusableCellWithIdentifier:@"cellName" forIndexPath:indexPath]; // "cellName" must be typed in on the cell, the storyboard // it the "identifier", NOT NOT NOT the restorationID [cell setupForNumber: thisRow]; cell.mainLabel.text = yourDataArray[ thisRow ][@"whatever"]; cell.otherLabel.text = yourDataArray[ thisRow ][@"whatever"]; return cell; }
hope this helps someone.
Sheila santos
source share