在 Tableview 中添加单选按钮有一些问题 [英] Add Radio Button in Tableview Got Some Problem

查看:18
本文介绍了在 Tableview 中添加单选按钮有一些问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 xcode 没有单选按钮

I know xcode don't have radio Button

所以我尝试添加一个自定义按钮并使其像单选按钮一样操作

so I try to add a custom button and make it action like a radio button

这是我使用的图像

这是我设置到单元格的代码

and this is the code I set to cell

UIButton *but = [UIButton buttonWithType:UIButtonTypeCustom];
[but setImage:[UIImage imageNamed:@"radio-off.png"] forState:UIControlStateNormal];
[but setImage:[UIImage imageNamed:@"radio-on.png"] forState:UIControlStateSelected];
[but setFrame:CGRectMake(0, 0, 44, 44)];
[but addTarget:self action:@selector(radioButton:) forControlEvents:UIControlEventTouchUpInside];
cell.accessoryView= but;

而这就是我要问的问题是

and this is the problem I want to ask is

如何在 - (IBAction)radioButton:(UIButton *)button

控制两行中的两个单选按钮

To control Two Radio Button in Two Rows

如果第 1 行单选按钮被选中是 YES

If Row 1 Radio button's selected is YES

第 2 行中的 btn 将是 btn.state=NO 并且不会响应

btn in row 2 will be btn.state=NO and won't response the

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

会是这样的图片

中如何设置if条件- (IBAction)radioButton:(UIButton *)button

这张图片是假的...我只在单元格中添加了按钮...并更改了文本颜色

this pic is fake...I only add the button in the cell...and changed the text color

非常感谢所有堆栈溢出的朋友~

Great Thanks to all stack overflow friends~

推荐答案

您需要一个包含所有单选按钮的数组.请记住,表格单元格会被回收/可能不可见等,因此仅使用按钮创建一个数组,然后在 tableView:cellForIndexPath: 方法中从该数组中获取右侧按钮.

You will need an array of all the radio buttons. Remember that table cells get recycled/may not be visible, etc. so create an array just with the buttons and then grab the right button out of that array in your tableView:cellForIndexPath: method.

所以在你的 tableView:cellForIndexPath: 方法中你会做这样的事情:

So in your tableView:cellForIndexPath: method you would do something like this:

cell.accessoryView = [myButtonArray objectAtIndex:[indexPath row]];

然后,在您的 radioButton: radioButtonPressed: 方法中,您将执行以下操作:

Then, in your radioButton: radioButtonPressed: method you would do:

// Select the pressed button.
[button setSelected:YES];
// Unselect all others.
for (UIButton *other in myButtonArray) {
    if (other != button) {
       [other setSelected:NO];
    }
}

这篇关于在 Tableview 中添加单选按钮有一些问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆