整体代码如下:
注:具体分的步骤只是根据demo来的
1、控件的初始化:(不用多说,都会)
allowsMultipleSelectionDuringEditing设置为YES tableview允许多选
- (void)viewDidLoad {
[super viewDidLoad];
self.testTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, M_SIZE.width, M_SIZE.height) style:UITableViewStyleGrouped];
self.testTableView.delegate = self;
self.testTableView.dataSource = self;
[self.view addSubview:self.testTableView];
textArry = @[@"one", @"two", @"three", @"four", @"five"];
// 控制tableview在可编辑状态下 - 可多选
self.testTableView.allowsMultipleSelectionDuringEditing = YES;
// 添加一个可以控制tableview编辑状态的按钮
UIButton *buttonEdit = [UIButton buttonWithType:UIButtonTypeCustom];
buttonEdit.frame = CGRectMake(M_SIZE.width - 40, M_SIZE.height - 40, 20, 20);
[buttonEdit setBackgroundColor:[UIColor orangeColor]];
[buttonEdit addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:buttonEdit];
}
2、button的点击事件:
[self.testTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];```
indexPath:指定选中cell所在的行和列
UITableViewScrollPosition:枚举类型 将选中的cell移动到tableview的指定位置
设置某cell未选中:
[self.testTableView deselectRowAtIndexPath:indexPath animated:YES];
- (void)buttonAction:(UIButton *)sender {
self.testTableView.editing = !self.testTableView.editing;
// 简单实现以下全选的效果 :
for (int i = 0; i < textArry.count; i++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
if (self.testTableView.editing) {
[self.testTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
// UITableViewScrollPosition 选中行滚动tableview的哪个位置
}else{
[self.testTableView deselectRowAtIndexPath:indexPath animated:YES];
}
}
}
######3、代理方法:(纯属废话)
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
} - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return textArry.count;
} - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellID = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
}
cell.tintColor = [UIColor redColor];
cell.textLabel.text = textArry[indexPath.row];
return cell;
}
默认对勾的颜色是蓝色,如果想修改选中对勾的颜色 需要设置cell的tintColor 如下:
cell.tintColor = [UIColor redColor];
选中与未选中的效果图如下:
![
![Simulator Screen Shot 2016年9月12日 下午6.03.38.png](https://img.haomeiwen.com/i1787970/ac5066bcf86a1df9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
](https://img.haomeiwen.com/i1787970/d8b92cdfa6fb9c73.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
至于全选删除的功能代码就需要自己研究逻辑了~
网友评论