iOS开发 tableView多选、全选的简单使用
以下两张图为全部代码(图片看着方便些,后面有代码可供复制参考)
全部代码
#import "ViewController.h"@interface ViewController ()@property(nonatomic,retain)UITableView *tableView;
@property(nonatomic,retain)NSMutableArray *dataSource;
@property(nonatomic,assign)BOOL isAllSelected;
@property(nonatomic,retain)NSMutableArray *selectData;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
for (int i=0; i<20; i++) {
[self.dataSource addObject:@(i)];
}
self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cellID"];
self.tableView.editing = YES;
self.tableView.delegate = self;
self.tableView.dataSource = self;
[self.view addSubview:self.tableView];
}
- (IBAction)printObjs:(UIBarButtonItem *)sender {
NSLog(@"%@",self.selectData);//打印当前选中的内容
NSLog(@"%@",[self.tableView indexPathsForSelectedRows]);//也可以根据当前选中的行号。对selectData进行赋值。建议使用该种方式。这种方式不需要在点击cell时去对selectData操作。只在需要时进行一次赋值即可。
}
- (IBAction)selectAll:(id)sender {
if (_isAllSelected == NO) {
_isAllSelected = YES;
[sender setTitle:@"取消"];
for (int i = 0; i < self.dataSource.count; i++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
[self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
}
[self.selectData addObjectsFromArray:self.dataSource];
} else {
_isAllSelected = NO;
[sender setTitle:@"全选"];
for (int i = 0; i < self.dataSource.count; i++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}
[self.selectData removeAllObjects];
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.dataSource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID" forIndexPath:indexPath];
cell.textLabel.text = [NSString stringWithFormat:@"%@",self.dataSource[indexPath.row]];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[self.selectData addObject:self.dataSource[indexPath.row]];
}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
[self.selectData removeObject:self.dataSource[indexPath.row]];
}
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
return UITableViewCellEditingStyleInsert|UITableViewCellEditingStyleDelete;
}
-(NSMutableArray *)dataSource{
if (!_dataSource) {
_dataSource = [[NSMutableArray alloc] initWithCapacity:0];
}
return _dataSource;
}
-(NSMutableArray *)selectData{
if (!_selectData) {
_selectData = [[NSMutableArray alloc] initWithCapacity:0];
}
return _selectData;
}
@end