iOS TableView Cell多选
2016-10-20 本文已影响280人
cb6a1e2768d1
多选其实就要解决一个问题:cell的复用(重用)
我喜欢的做法是设置一个字典记录选中的cell
@interface ExampleView()
@property (nonatomic, strong) NSMutableDictionary *dict;
@end
- (NSMutableDictionary *)dict{
if (_dict == nil) {
_dict = [NSMutableDictionary dictionary];
}
return _dict;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier=@"cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(!cell){
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
if ([_dict[[NSString stringWithFormat:@"%zd",indexPath.row]] length]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}else{
cell.accessoryType = UITableViewCellAccessoryNone;
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
self.dict[[NSString stringWithFormat:@"%zd",indexPath.row]] = [NSString stringWithFormat:@"%zd",indexPath.row];
UITableViewCell *selectCell = [tableView cellForRowAtIndexPath:indexPath];
if (selectCell.accessoryType == UITableViewCellAccessoryCheckmark) {
selectCell.accessoryType = UITableViewCellAccessoryNone;
}else{
selectCell.accessoryType = UITableViewCellAccessoryCheckmark;
}
}
多选简单的就这样存成字典,复杂的可以存成模型。
一个有趣的地方在
[_dict[[NSString stringWithFormat:@"%zd",indexPath.row]] length]
判断cell时候选中过,我判断字典的值的长度而不是跟indexPath.Row相比较
一开始是想比较如果相等则cell是选中状态,否则未选中
但后来试了一下,取出字典null,转换成数字类型铁定是0
所以第一个cell即使没有选中也会被默认选中
不符合需求。