I am having some difficulty properly setting the selectedBackgroundView for a UITableViewCell in the cellForRowAtIndexPath method. I have tried a few code variations...
CGRect customFrame = CGRectMake(cell.frame.origin.x + 1.0f, cell.frame.origin.y,
cell.frame.size.width - 22.0f, cell.frame.size.height);
UIView *cellBackground = [[[UIView alloc] initWithFrame:customFrame] autorelease];
cellBackground.backgroundColor = [UIColor colorWith8BitRed:0 green:0 blue:0 alpha:0.1f];
cell.selectedBackgroundView = cellBackground;
With this snippet, the cell exhibits the proper color change, but the frame dimensions are not what I specified (they seem to be the dimensions of cell.frame even though I specified the view to initialize with my customFrame)
I have tried one more approach: creating a parent view with a child subview. The parent view 's frame are the same dimensions as the cell, and the child subview's frame contains my customFrame dimensions. When I set the parent view as the backgroundView, my frame customFrame dimensions are applied. However, when I attempt to set the parent view as the selectedBackgroundView, I see no view when selecting a cell.
CGRect customFrame = CGRectMake(cell.frame.origin.x + 1.0f, cell.frame.origin.y,
cell.frame.size.width - 22.0f, cell.frame.size.height);
UIView *parentView = [[[UIView alloc] initWithFrame:cell.frame] autorelease];
UIView *childView = [[[UIView alloc] initWithFrame: customFrame] autorelease];
[parentView addSubview:childView];
childView.backgroundColor = [UIColor colorWith8BitRed:0 green:0 blue:0 alpha:0.1f];
cell.selectedBackgroundView = parentView;
It seems rather difficult to customize the selectedBackgroundView's frame dimensions. Any help would be appreciated. Thanks!
You need this in your Custom TableViewCell
- (void)layoutSubviews
{
[super layoutSubviews];
self.selectedBackgroundView.frame = CGRectMake(cell.frame.origin.x + 1.0f, cell.frame.origin.y, cell.frame.size.width - 22.0f, cell.frame.size.height);
}
I had to scratch my head. It's kind of stupid because one way or another you need twice the frame. Of course you can use define or even a property to the UIView itself, but still...
I could only find that thanks to Ortwin Gentz — Props to him!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With