tableView选择多项或单选

多选数组

第一步:初始化model加入可变数组spa

- (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];
}

单选code

与多选的区别在于代理方法的处理不一样orm

- (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];
    
}
相关文章
相关标签/搜索