UITbaleView上按钮的单选

设置Id属性,标记是哪个cell

@property (nonatomic,assign)NSInteger Id;

设置一个普通状态和选中状态图片不同的按钮

  _choose = [[UIButton alloc]init];

        [_choose setImage:[UIImage imageNamed:@"about_未勾选"] forState:UIControlStateNormal];

        [_choose setImage:[UIImage imageNamed:@"about_勾选"] forState:UIControlStateSelected];

        [_choose addTarget:self action:@selector(choosePressed:) forControlEvents:UIControlEventTouchUpInside];

        [self.contentView addSubview:_choose];
- (void)layoutSubviews {

    _choose.frame = CGRectMake(10, 120+wei_tiao, 20, 20);

}

设置一个可调整选中或者为选中的方法

- (void)setChecked:(BOOL)checked {

    if (checked) {

        _choose.selected = YES;

    }else {

        _choose.selected = NO;

    }

}

cell上按钮的单击事件

/**

 *  选择勾选

 *

 *  @param sender 按钮

 */

- (void)choosePressed:(UIButton *)sender {

    sender.selected = YES;

    if (_chooseBlock) {

        _chooseBlock(self.Id);

    }

}

设置一个全局变量来判定点了哪一个cell

    NSInteger _cellIndex;

 

tableView代理:- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    ShippingAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID"];

    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    cell.Id = indexPath.row;

    if (_cellIndex == indexPath.row) {

        [cell setChecked:YES];

    }else {

        [cell setChecked:NO];

    }

    [cell setChooseBlock:^(NSInteger index) {

        _cellIndex = index;

        [_tableView reloadData];

    }];

    return cell;

}

效果图:

 

补:使用了block作为属性回调

1.申明block属性

@property (copy, nonatomic) void(^chooseBlock)(NSInteger index);

2.在本类里面调用

 if (_chooseBlock) {

        _chooseBlock(self.Id);

    }

3.使用block属性:

  [cell setChooseBlock:^(NSInteger index) {

        _cellIndex = index;

        [_tableView reloadData];

    }];

 

你可能感兴趣的:(view)