我在表格 View 单元格中有一个单选按钮。这是我的单选按钮
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myCell"];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"myCell"];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIButton *newRadioButton = [UIButton buttonWithType:UIButtonTypeCustom];
newRadioButton.frame = CGRectMake(30, 0, 15, 14.5);
[newRadioButton setImage:[UIImage imageNamed:@"unselect"] forState:UIControlStateNormal];
[newRadioButton setImage:[UIImage imageNamed:@"select"] forState:UIControlStateSelected];
cell.accessoryView = newRadioButton;
if ([indexPath isEqual:selectedIndex])
{
newRadioButton.selected = YES;
}
else
{
newRadioButton.selected = NO;
}
}
cell.textLabel.text = [array objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
selectedIndex = indexPath;
[table reloadData];
}
-(void)radiobtn:(id)sender
{
if([sender isSelected])
{
[sender setSelected:NO];
} else
{
[sender setSelected:YES];
}
}
它的工作,但我想一次只选择一个单选按钮,就像这个图像(左)。但对我来说,选择所有单选按钮(右)。
我需要让它看起来像第一张图片。
最佳答案
我认为你应该尝试:
在 YourViewController.h 中
@interface YourViewController : UITableViewController {
NSIndexPath *selectedIndex
}
在 YourViewController.m 中
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myCell"];
if(cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"myCell"];
UIButton *newRadioButton;
newRadioButton = [UIButton buttonWithType:UIButtonTypeCustom];
newRadioButton.frame = CGRectMake(30, 0, 15, 14.5);
[newRadioButton setImage:[UIImage imageNamed:@"unselect"] forState:UIControlStateNormal];
[newRadioButton setImage:[UIImage imageNamed:@"select"] forState:UIControlStateSelected];
cell.accessoryView = newRadioButton;
}
if ([indexPath isEqual:selectedIndex]) {
newRadioButton.seleted = YES;
} else {
newRadioButton.seleted = NO;
}
cell.textLabel.text = [array objectAtIndex:indexPath.row];
return cell;
}
和
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
selectedIndex = indexPath;
[tableView reloadData];
}
这个link可能对你有帮助
关于ios - 如何在表格 View 中一次选择单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28624528/