UITableViewCell改變選中時背景樣式
1、如果不想讓選中狀態下cell的背景發生改變:
cell.selectionStyle = UITableViewCellSelectionStyleNone;
2、自定義未選擇下cell的背景:
可以通過cell自帶的的backgroundView:
cell.backgroundView = [[UIViewalloc] init];
cell.backgroundView.backgroundColor = [[UIColoralloc] initWithPatternImage:[UIImageimageNamed:@"bg"]];
3、改變cell選中時背景色
可以通過cell的selectedBackgroundView
cell.selectedBackgroundView = [[UIViewalloc] init];
cell.selectedBackgroundView.backgroundColor = [[UIColoralloc] initWithPatternImage:[UIImageimageNamed:@"bg"]];
第2和第3配合可以方便的實現,cell選中和未選中時的cell背景轉換或是標示選中狀態:
eg,如果想在cell(A)被選中時左邊新增一個標誌,選中另外一個cell(B)時,A自動恢復為未選中狀態:
可能你腦海中很快就想到解決方法:定義一個變數跟中cell的狀態用語恢復未選中狀態。
其實有更優雅的解決方法,就是使用cell自帶的selectedBackgroundView:
比如:在cell被選中時,cell左邊有條紅色的豎線,未選擇時則隱藏:
UIView *vLine = [[UIViewalloc] initWithFrame:CGRectMake(0, 0, 2, 30)];
vLine.backgroundColor = [UIColor orangeColor];
cell.backgroundView = [[UIView alloc] init];
[cell.backgroundViewvLine];
這樣就可以了,不需要去跟蹤cell的狀態,更不需要每次選中逗reload一次。