Why does my custom cell only highlight when the user removes their finger?
I have created a custom UITableViewCell, and set the backgroundView with the following code:
- (void)layoutSubviews
{
开发者_如何学运维 [super layoutSubviews];
self.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"NormalImage"]];
self.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"HighlightedImage"]];
// other layout stuff
}
This works fine except that, when the user selects a row, it does not highlight - it only highlights when the user lifts off their finger (so you briefly see it highlight before transitioning to the next view). If I remove the self.selectedBackgroundView
line, so that there is the normal iOS blue cell highlight, it will highlight as soon as the cell is selected.
Why is this?
Try this code in the custom table cell
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated
{
[super setHighlighted:highlighted animated:animated];
if (highlighted) {
self.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"HighlightedImage"]];
} else {
self.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"NormalImage"]];
}
}
You can assign backgroundView and selectedBackgroundView when initializing your custom cell. According to apple's doc, the selectedBackgroudView is used as the background when the cell is selected.
If you write those codes in -(void)layoutSubviews, when the cell is selected, or unselected, it will call -(void)layoutSubviews. Then, your backgroundView and selectedBackgroundview will be re-assigned to new UIView instances each time when the state of custom cell has been changed.
精彩评论