Tableview单元格iOS中的RadioButton

时间:2016-08-10 10:03:22

标签: ios radio-button tableview selection

我已经关注了RadioButton的this教程。我已经将它与tableview集成。问题是,当我选择表格行时,单选按钮不会被选中。只有在我点击RadioButton时它才会被选中。我希望在选择表格行时选择单选按钮。代码如下:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *simpleTableIdentifier = @"SimpleTableItem";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

    if (cell == nil) {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];

    }
    RadioButton *rb1 = [[RadioButton alloc] initWithGroupId:@"Group" index:indexPath.row];
    rb1.frame = CGRectMake(20,13,22,22);
    [cell.contentView addSubview:rb1];
    cell.textLabel.text = @"ABC";
    return cell;
}

RadioButton with Tableview

2 个答案:

答案 0 :(得分:1)

didSelectRowAtIndexPath

上执行以下代码

目标C

 -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        UIButton *btn = (UIButton *)[cell viewWithTag:101];
        [btn setBackgroundImage:[self imageWithColor:[UIColor redColor]] forState:UIControlStateSelected];
        btn.selected = YES;
        NSLog(@"Button : %@",btn);
    }



    - (UIImage *)imageWithColor:(UIColor *)color {
        CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
        UIGraphicsBeginImageContext(rect.size);
        CGContextRef context = UIGraphicsGetCurrentContext();

        CGContextSetFillColorWithColor(context, [color CGColor]);
        CGContextFillRect(context, rect);

        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        return image;
    }

答案 1 :(得分:1)

//在" cellforRowAtIndexpath"

中将标签设置为您的Btn
rb1.tag=101;

在didSelectRowAtIndexPath - >

UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
UIButton *btn = (UIButton*)[cell viewWithTag:101]; 
 btn.backgroundColor=[UIColor redColor];
btn.Selected = YES;
 [btn handleButtonTap:self];