tableviewcell的單選和多選
阿新 • • 發佈:2019-02-08
iOS開發中,有時候需要實現tableView中cell的單選或者複選,這裡舉例說明了怎麼簡單的實現
首先自己建立一個列表,實現單選,先定義一個變數記錄每次點選的cell的indexPath:
@property (assign, nonatomic) NSIndexPath *selIndex;//單選,當前選中的行
- 1
- 1
然後在下面的代理方法實現程式碼
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//之前選中的,取消選擇
UITableViewCell *celled = [tableView cellForRowAtIndexPath:_selIndex];
celled.accessoryType = UITableViewCellAccessoryNone;
//記錄當前選中的位置索引
_selIndex = indexPath;
//當前選擇的打勾
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
當然,上下滑動列表的時候,因為cell的複用,需要在下面的方法再判斷是誰打勾
//當上下拉動的時候,因為cell的複用性,我們需要重新判斷一下哪一行是打勾的
if (_selIndex == indexPath) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 1
- 2
- 3
- 4
- 5
- 6
這樣就實現的單選的功能了
接下來說一下多選的實現,和單選不同,多選是一組位置座標,所以我們需要用陣列把這一組選中的座標記錄下來,定義一個數組
@property (strong, nonatomic) NSMutableArray *selectIndexs;//多選選中的行
- 1
- 1
初始化一下
_selectIndexs = [NSMutableArray new];
- 1
- 1
接下來還是在下面的代理方法實現程式碼
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//獲取到點選的cell
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryCheckmark) { //如果為選中狀態
cell.accessoryType = UITableViewCellAccessoryNone; //切換為未選中
[_selectIndexs removeObject:indexPath]; //資料移除
}else { //未選中
cell.accessoryType = UITableViewCellAccessoryCheckmark; //切換為選中
[_selectIndexs addObject:indexPath]; //新增索引資料到陣列
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
當然也需要在下面的方法做處理
//設定勾
cell.accessoryType = UITableViewCellAccessoryNone;
for (NSIndexPath *index in _selectIndexs) {
if (index == indexPath) { //改行在選擇的數組裡面有記錄
cell.accessoryType = UITableViewCellAccessoryCheckmark; //打勾
break;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
複選: