2019独角兽企业重金招聘Python工程师标准>>>
多选
第一步:初始化model加入可变数组
- (void)initWithData {
_dataArray = [NSMutableArray arrayWithCapacity:1];
for (int i=0; i<20; i++) {
SelectedModel *sModel = [[SelectedModel alloc] init];
sModel.title = [NSString stringWithFormat:@"%d", i];
sModel.isSelected = NO;
[_dataArray addObject:sModel];
}
}
第二步:在代理中实现选中取消选中的状态
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
SelectedModel *model = _dataArray[indexPath.row];
model.isSelected = !model.isSelected;
[_dataArray replaceObjectAtIndex:indexPath.row withObject:model];
[self.myTableView reloadData];
}
单选
与多选的区别在于代理方法的处理不同
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if (_lastIndex != -1) {
SelectedModel *sModel = _dataArray[_lastIndex];
sModel.isSelected = NO;
[_dataArray replaceObjectAtIndex:_lastIndex withObject:sModel];
}
_lastIndex = indexPath.row;
SelectedModel *model = _dataArray[indexPath.row];
model.isSelected = YES;
[_dataArray replaceObjectAtIndex:indexPath.row withObject:model];
[self.myTableView reloadData];
}