查看UITableViewCell的幫助文檔我們可以看到它有兩個屬性highLighted、selected。
這兩者之間到底又怎麼樣的聯繫呢?當我們點擊cell的時候都發生了什麼呢?
要達到這個目的,很簡單我們只要自定義一個cell繼承自UITableViewCell,然後重載它的以下兩個方法:
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated;
- (void)setSelected:(BOOL)selected animated:(BOOL)animated;
這兩個方法一個是設置cell的高亮狀態,另一個是設置cell的選中狀態,
- (void)setSelected:(BOOL)selected animated:(BOOL)animated { [super setSelected:selected animated:animated]; if (selected) { _contentLbl.textColor = [UIColor whiteColor]; } else { _contentLbl.textColor = [UIColor blackColor]; } } - (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated { [super setHighlighted:highlighted animated:animated]; if (highlighted) { _contentLbl.textColor = [UIColor whiteColor]; } else { _contentLbl.textColor = [UIColor blackColor]; } }
當我們點擊cell的時候,其實是先設置cell的高亮狀態爲YES,然後鬆手的時候再將cell的高亮狀態設置爲NO,
接着纔是設置cell的選中狀態爲YES,
最後纔會去調用delegate中的tableview:didSelectRowAtIndexPath:方法。
注:默認選中一行UITableViewCell
NSIndexPath *firstPath = [NSIndexPath indexPathForRow:0 inSection:0];
[_tableView selectRowAtIndexPath:firstPath animated:NO scrollPosition:UITableViewScrollPositionTop];//默認選中一行