你的位置:首页 > 操作系统

[操作系统]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;}

效果图: