我最近在做的一個項目中遇到了單元格單選的功能,當時我的第一想法是在單元格上添加按鈕,通過點擊改變按鈕的背景圖片并記錄最后一次點擊的indexPath,因為之前的項目中遇到過多選的功能,用這種方法出現了復用的問題,也就是選擇某個單元格滑動表格時沒點擊的單元格也被選中了,所以當時就很擔心單選的時候出現同樣的問題,果不其然,只顯示最后一個單元格被選中。然后我找到了這種方法,總結了一下
這個功能的實現只需要在兩個方法中code即可
首選我們公開一個屬性
@property(nonatomic,strong)NSIndexPath *lastPath;
主要是用來接收用戶上一次所選的cell的indexpath
第一步:在cellForRowAtIndexPath:方法中實現如下代碼
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSInteger row = [indexPath row];
NSInteger oldRow = [lastPath row];
if (row == oldRow && lastPath!=nil) {
//這個是系統中對勾的那種選擇框
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}else{
cell.accessoryType = UITableViewCellAccessoryNone;
}
}
第二步:在didSelectRowAtIndexPath:中實現如下代碼
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//這里最好不要聲明int類型的,個人建議
NSInteger newRow = [indexPath row];
NSInteger oldRow = (self .lastPath !=nil)?[self .lastPath row]:-1;
if (newRow != oldRow) {
UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath];
newCell.accessoryType = UITableViewCellAccessoryCheckmark;
UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:lastPath];
oldCell.accessoryType = UITableViewCellAccessoryNone;
self .lastPath = indexPath;
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
Ok,可以收工了,這樣實現之后的效果是每次單擊一個cell會做一個選中的標志并且托動表視圖時也不會出現checkmark的復用
不過,根據項目需求,可能會需要定義一個按鈕,自定義選擇框的圖片,這也很簡單,只需要將上面的代碼改一下就ok了:
在cellForRowAtIndexPath:中如下修改
if (row == oldRow && self.lastPath!=nil) {
[cell . selectBtn setBackgroundImage:[UIImage imageNamed:@"選中點"] forState:UIControlStateNormal];
}else{
[cell . selectBtn setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
}
在didSelectRowAtIndexPath:中如下修改
if (newRow != oldRow) {
self.cell = [tableView cellForRowAtIndexPath:indexPath];
[self .cell.selectBtn setBackgroundImage:[UIImage imageNamed:@"選中點"] forState:UIControlStateNormal];
self.cell = [tableView cellForRowAtIndexPath:self .lastPath];
[self .cell.selectBtn setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
self .lastPath = indexPath;
}