天天看點

UITableViewCell改變選中時背景樣式

1、如果不想讓選中狀态下cell的背景發生改變:

 cell.selectionStyle = UITableViewCellSelectionStyleNone;

2、自定義未選擇下cell的背景:

可以通過cell自帶的的backgroundView:

 cell.backgroundView = [[UIView alloc] init];

 cell.backgroundView.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"bg"]];

3、改變cell選中時背景色

可以通過cell的selectedBackgroundView

 cell.selectedBackgroundView = [[UIView alloc] init];

 cell.selectedBackgroundView.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"bg"]];

第2和第3配合可以友善的實作,cell選中和未選中時的cell背景轉換或是标示選中狀态:

eg,如果想在cell(A)被選中時左邊添加一個标志,選中另外一個cell(B)時,A自動恢複為未選中狀态:

可能你腦海中很快就想到解決方法:定義一個變量跟中cell的狀态用語恢複未選中狀态。

其實有更優雅的解決方法,就是使用cell自帶的selectedBackgroundView:

比如:在cell被選中時,cell左邊有條紅色的豎線,未選擇時則隐藏:

UIView *vLine =  [[UIView alloc] initWithFrame:CGRectMake(0, 0, 2, 30)];

vLine.backgroundColor = [UIColor orangeColor];

cell.backgroundView = [[UIView alloc] init];

[cell.backgroundView vLine];

這樣就可以了,不需要去跟蹤cell的狀态,更不需要每次選中逗reload一次。