開發工作中經常遇到列表編輯多選功能,UITableView其實自帶的有多選功能,使用起來方便,不需要自己做選中狀態,效果:
獲取多選cell的位置信息:
- (NSArray*)indexPathsForSelectedRows;
在? didSelectRowAtIndexPath:方法里獲取并打印選中cell的位置信息:
- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath {
NSArray*selectCells = [tableView indexPathsForSelectedRows];
NSLog(@"------%@",selectCells);
}
打印結果:
2017-01-25 16:21:15.088 cocopodsText[655:17134] ------(
" {length = 2, path = 0 - 2}",
" {length = 2, path = 0 - 4}",
" {length = 2, path = 0 - 7}",
" {length = 2, path = 0 - 10}",
" {length = 2, path = 0 - 8}",
" {length = 2, path = 0 - 6}"
)
數組結果里是按照選中的順序存儲的數據。
接下來先說說全選和全不選的操作,以下都是在單section情況下:
全選:
遍歷一遍數據源 然后選中每一條:
//全選按鈕事件
- (void)allSelectAction:(UIButton*)sender {
[self.dataSource enumerateObjectsUsingBlock:^(id_Nonnullobj,NSUIntegeridx,BOOL*_Nonnullstop) {
[self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:idx inSection:0]animated:NOscrollPosition:UITableViewScrollPositionNone];
}];
}
全不選:
全不選,reload就可以變為全不選狀態了,如果不想reload這樣簡單粗暴的,也可以取出當前選中的indexpath數組,遍歷反選也可以。
//全不選按鈕事件
- (void)allUnSelectAction:(UIButton*)sender {
[[self.tableView indexPathsForSelectedRows]enumerateObjectsUsingBlock:^(NSIndexPath*_Nonnullobj,NSUIntegeridx,BOOL*_Nonnullstop) {
[self.tableView deselectRowAtIndexPath:objanimated:NO];
}];
}
引用文章:www.lxweimin.com/p/a6e4cb42dd03
UITableView相關方法使用詳細介紹: