我的tableview包含两个部分,每个部分包含n个行数,其中每个部分的第一行没有单选按钮。我发现编写一组选定的单选按钮很困难。
在这个例子中,“越狱”和“家园”是我的部分。此部分包含6行。只有4行有单选按钮,我需要相应地在这两个之间切换。
我试过在cellForRowAtIndexPath中创建所有radiobutton数组:并且在为每个按钮添加目标时,我正在取消所有其他按钮。
-(IBAction)toggleButton:(UIButton *)button{
//select the tapped radio button.
button.selected = !button.selected;
// Unselect all others.
for (id key in _myButtonDict) {
UIButton *btn = [_myButtonDict valueForKey:key];
NSLog(@"%ld",(long)btn.tag);
if ([_myButtonDict valueForKey:key] != button) {
[[_myButtonDict valueForKey:key] setSelected:NO];
}
} }
答案 0 :(得分:0)
@interface RadioButton : UIButton
@property (nonatomic,assign) NSInteger *row;
@property (nonatomic,assign) NSInteger *section;
@end
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//create a tableviewcell
//add the radio button to each cell.
RadioButton *radioButton = [RadioButton buttonWithType:UIButtonTypeCustom];
[radioButton setImage:[UIImage imageNamed:@"uncheck.png"] forState:UIControlStateNormal];
[radioButton setImage:[UIImage imageNamed:@"check.png"] forState:UIControlStateSelected];
//radiobutton properties.
radioButton.tag = indexPath.section;
radioButton.row = indexPath.row;
[radioButton addTarget:self action:@selector(toggleButton:) forControlEvents:UIControlEventTouchUpInside];
cell.accessoryView = radioButton;
return cell;
}