iOS開發(fā)中亲桦,有時候需要實現(xiàn)tableView中cell的單選或者復(fù)選缎谷,這里舉例說明了怎么簡單的實現(xiàn)
首先自己創(chuàng)建一個列表,實現(xiàn)單選蚁孔,先定義一個變量記錄每次點擊的cell的indexPath:
@property (assign, nonatomic) NSIndexPath *selIndex;//單選屑埋,當(dāng)前選中的行
然后在下面的代理方法實現(xiàn)代碼
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//之前選中的豪筝,取消選擇
UITableViewCell *celled = [tableView cellForRowAtIndexPath:_selIndex];
celled.accessoryType = UITableViewCellAccessoryNone;
//記錄當(dāng)前選中的位置索引
_selIndex = indexPath;
//當(dāng)前選擇的打勾
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
當(dāng)然,上下滑動列表的時候雀彼,因為cell的復(fù)用壤蚜,需要在下面的方法再判斷是誰打勾
這里寫圖片描述
//當(dāng)上下拉動的時候,因為cell的復(fù)用性徊哑,我們需要重新判斷一下哪一行是打勾的
if (_selIndex == indexPath) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
這樣就實現(xiàn)的單選的功能了
這里寫圖片描述
接下來說一下多選的實現(xiàn),和單選不同聪富,多選是一組位置坐標(biāo)莺丑,所以我們需要用數(shù)組把這一組選中的坐標(biāo)記錄下來,定義一個數(shù)組
@property (strong, nonatomic) NSMutableArray *selectIndexs;//多選選中的行
初始化一下
_selectIndexs = [NSMutableArray new];
接下來還是在下面的代理方法實現(xiàn)代碼
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//獲取到點擊的cell
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryCheckmark) { //如果為選中狀態(tài)
cell.accessoryType = UITableViewCellAccessoryNone; //切換為未選中
[_selectIndexs removeObject:indexPath]; //數(shù)據(jù)移除
}else { //未選中
cell.accessoryType = UITableViewCellAccessoryCheckmark; //切換為選中
[_selectIndexs addObject:indexPath]; //添加索引數(shù)據(jù)到數(shù)組
}
}
當(dāng)然也需要在下面的方法做處理
這里寫圖片描述
//設(shè)置勾
cell.accessoryType = UITableViewCellAccessoryNone;
for (NSIndexPath *index in _selectIndexs) {
if (index == indexPath) { //改行在選擇的數(shù)組里面有記錄
cell.accessoryType = UITableViewCellAccessoryCheckmark; //打勾
break;
}
}
復(fù)選:
這里寫圖片描述