您应该创建一个函数来检查您的自定义单元格中的单选按钮,并实现一个委托方法来通知您的 TableViewController 您选择了该单元格上的按钮。
您的 TableViewController 需要实现该委托(不要忘记设置每个 cell.delegate = self)。
然后在您的委托方法中创建一个循环以取消选中该部分中除您刚刚选中的单元格之外的所有单元格的单选按钮。
类似的东西:
这是一个带有按钮的自定义 UITableViewCell。
选中和取消选中的图像需要看起来像选中和取消选中的单选按钮
这是 .h 文件:
//RadioCell.h
@protocol RadioCellDelegate <NSObject>
-(void) myRadioCellDelegateDidCheckRadioButton:(RadioCell*)checkedCell;
@end
@interface RadioCell : UITableViewCell
-(void) unCheckRadio;
@property (nonatomic, weak) id <RadioCellDelegate> delegate;
@end
这是 RadioCell 的 .m 文件
//RadioCell.m
@property (nonatomic, assign) UIButton myRadio;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString*)reuseIdentifier
_myRadio = [UIButton buttonWithType:UIButtonTypeCustom];
[_myRadio setImage:[UIImage imageNamed:@"uncheck"] forState:UIControlStateNormal];
[_myRadio setImage:[UIImage imageNamed:@"check"] UIControlStateSelected];
[_myRadio addTarget:self action:@selector(radioTouched)orControlEvents:UIControlEventTouchUpInside];
_myRadio.isSelected = NO;
//don't forget to set _myRadio frame
[self addSubview:_myRadio];
}
-(void) checkRadio {
_myradio.isSelected = YES;
}
-(void) unCheckRadio {
_myradio.isSelected = NO;
}
-(void) radioTouched {
if(_myradio.isSelected == YES) {
return;
}
else {
[self checkRadio]
[_delegate myRadioCellDelegateDidCheckRadioButton:self];
}
}
现在只需使用 RadioCell(在 .m 文件中)调整您的 tableview 控制器
//MyTableViewController.m
@interface MyTableViewController () <RadioCellDelegate>
@end
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"RadioCell";
RadioCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[RadioCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel = @"Coke"; //or whatever you want
cell.delegate = self;
return cell;
}
-(void) myRadioCellDelegateDidCheckRadioButton:(RadioCell*)checkedCell {
NSIndexPath *checkPath = [self.tableView indexPathForCell:checkedCell];
for (int section = 0; section < [self.tableView numberOfSections]; section++) {
if(section == checkPath.section) {
for (int row = 0; row < [self.tableView numberOfRowsInSection:section]; row++) {
NSIndexPath* cellPath = [NSIndexPath indexPathForRow:row inSection:section];
RadioCell* cell = (CustomCell*)[tableView cellForRowAtIndexPath:cellPath];
if(checkPath.row != cellPath.row) {
[cell unCheckRadio];
}
}
}
}
}