我想使用自定义单元格创建动态单选按钮。我尝试并能够使用故事板创建。但如何只允许一个单选按钮选择?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MChangeServiceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"changeServiceCellidentifier"];
cell.serviceLabelView.text =@"test";
cell.radioButton.tag=indexPath.row;
[cell.radioButton addTarget:self action:@selector(radioButtonColorChange:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
- (void)radioButtonColorChange:(id)sender
{
UIButton *button=(UIButton *) sender;
NSIndexPath *indexpath = [NSIndexPath indexPathForRow:button.tag inSection:0];
MChangeServiceTableViewCell *tappedCell = (MChangeServiceTableViewCell *)[self.listTableView cellForRowAtIndexPath:indexpath];
if ([tappedCell.radioButton.imageView.image isEqual:[UIImage imageNamed:@"radio_button_unselected.png"]])
{
[tappedCell.radioButton setImage:[UIImage imageNamed:@"radio_button_selected.png"] forState:UIControlStateNormal];
}
else
{
[tappedCell.radioButton setImage:[UIImage imageNamed:@"radio_button_unselected.png"] forState:UIControlStateNormal];
}
}
我可以通过点击它来更改单选按钮的图像。但是如何在单击一个按钮时将剩余的单选按钮更改为未选中状态?
答案 0 :(得分:0)
我建议你将当前选中的按钮保存在另一个变量中。
@interface YourViewController ()
@property (strong, nonatomic) UIButton *currentBtn;
@property (nonatomic) NSInteger currentSelectedIndex;
@end
然后
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_currentSelectedIndex = -1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MChangeServiceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"changeServiceCellidentifier"];
cell.serviceLabelView.text =@"test";
cell.radioButton.tag=indexPath.row;
[cell.radioButton setImage:[UIImage imageNamed:@"radio_button_selected.png"] forState:UIControlStateSelected];
[cell.radioButton setImage:[UIImage imageNamed:@"radio_button_unselected.png"] forState:UIControlStateNormal];
[cell.radioButton addTarget:self action:@selector(radioButtonColorChange:) forControlEvents:UIControlEventTouchUpInside];
[cell.radioButton setSelected:NO];
if (indexPath.row == _currentSelectedIndex) {
[cell.radioButton setSelected:YES];
_currentBtn = cell.radioButton;
}
return cell;
}
- (void)radioButtonColorChange:(id)sender
{
_currentBtn.selected = NO;
UIButton *button=(UIButton *) sender;
button.selected = !button.isSelected;
_currentBtn = button;
_currentSelectedIndex = button.tag;
}