e ..一般多选 大家会想到使用一个自定义数组与indexPath进行关联。进行多选。进行ui变化。
其实UITableView已经自带了多选功能,状态由UITableView本身维护。代码很简单。直接上代码了。
一.设置可以多选
//非编辑模式下进行多选 self.tableView.allowsMultipleSelection = YES; //编辑模式下也有对应方法 //self.tableView.allowsMultipleSelectionDuringEditing = YES;
现在就可以进行多选啦。
二.设置选中后Cell的accessoryType或者自定义的图标。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"SelectCell";
[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:CellIdentifier];
UITableViewCell *cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.tintColor = [UIColor grayColor];
// cell.textLabel.textColor = self.titleColor?:[UIColor blackColor];
cell.textLabel.text = [[_newsArray objectAtIndex:indexPath.row] objectForKey:@"value"];
//防止重用后状态错乱.如果已经被选中,改变cell样式
if ([[tableView indexPathsForSelectedRows] containsObject:indexPath]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}else{
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//如果已经被选中,改变cell样式
UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
//如果取消选中,改变cell样式
UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryNone;
}
三.获取选中后的所有行或者数据
self.tableView.indexPathsForSelectedRows 就行当前选中的所有的行,重用也不会使他数据错误。相当于我们自己维护的状态数组啦。
NSMutableArray *selectItems =[NSMutableArray array];
for (NSIndexPath *indexPath in self.tableView.indexPathsForSelectedRows) {
NSDictionary *item = [_newsArray objectAtIndex:indexPath.row];
[selectItems addObject:item];
}
Done!