如何在uitableview中添加单选按钮?

时间:2018-03-21 08:15:14

标签: ios objective-c uitableview radio-button

我在桌面视图单元格中添加了按钮,我想在用户点击单元格时选择一个按钮

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

    static NSString *cellIdentifier = @"cell";
    UITableViewCell *cell = [theTableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        _radioButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _radioButton.frame = CGRectMake(30, 0, 30, 30);
        [_radioButton setImage:[UIImage imageNamed:@"radio_empty.png"] forState:UIControlStateNormal];
        [_radioButton setImage:[UIImage imageNamed:@"radio.png"] forState:UIControlStateSelected];
        cell.accessoryView = _radioButton;
        _radioButton.tag = indexPath.row;
    }

   if ([indexPath isEqual:selectedIndex])
    {
        _radioButton.selected = YES;
    }
    else
    {
        _radioButton.selected = NO;
    }

    cell.textLabel.text = [self.Option objectAtIndex:indexPath.row];

return cell;
}

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

   selectedIndex = indexPath;
   [theTableView reloadData];
   //I tried this also but not working
   if (_radioButton.tag == indexPath.row) {
        [_radioButton setImage:[UIImage imageNamed:@"radio.png"] forState:UIControlStateSelected];
    }
}

我尝试了很多。但它不起作用。 我想在用户点击单元格时显示所选图像。如果我们使用按钮或图像视图

1 个答案:

答案 0 :(得分:0)

我得到了这样的解决方案。

NSString *selectedIndex;

- (void)tableView:(UITableView *)theTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [theTableView deselectRowAtIndexPath:indexPath animated:NO];
    if(indexPath.row != [selectedIndex intValue]) {
        // reset the active account
        selectedIndex = [@(indexPath.row) stringValue];

        // tell the table to rebuild itself
        [theTableView reloadData];
    }
}

- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"cell";
    UITableViewCell *cell = [theTableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }

    if(indexPath.row == [selectedIndex intValue]) {
        cell.imageView.image = [UIImage imageNamed:@"radio.png"];
    }
    else {
        cell.imageView.image = [UIImage imageNamed:@"radio_empty.png"];
    }
    cell.textLabel.text = [self.Option objectAtIndex:indexPath.row];
 return cell;
} 
相关问题