如何在自定义单元格中保存多个选定的按钮?

时间:2015-12-16 13:43:19

标签: ios uitableview custom-cell

在我的自定义单元格中有很多问题和答案,在每个部分我想选择任何一个按钮,那个按钮怎么能存储呢?在CellForRowAtIndexPath中,我为每个答案创建了目标, 这是我的代码!

-(void)buttonsClicked:(id)sender
 {
    UIButton *btn=(UIButton*)sender;

    ContestQATableViewCell * cell=(ContestQATableViewCell *)[btn.superview superview];
    if (cell.answer1.tag==btn.tag)
    {
        NSLog(@"%ld",(long)btn.tag);
        [cell.answer1 setImage:[UIImage imageNamed:@"RadioChecked"] forState:UIControlStateNormal];
    }else{

        [cell.answer1 setImage:[UIImage imageNamed:@"RadioUnChecked"] forState:UIControlStateNormal];
    }
    if (cell.answer2.tag==btn.tag)
    {
        NSLog(@"%ld",(long)btn.tag);
        [cell.answer2 setImage:[UIImage imageNamed:@"RadioChecked"] forState:UIControlStateNormal];
    }else{

        [cell.answer2 setImage:[UIImage imageNamed:@"RadioUnChecked"] forState:UIControlStateNormal];
    }
    if (cell.answer3.tag==btn.tag)
    {
        NSLog(@"%ld",(long)btn.tag);
        [cell.answer3 setImage:[UIImage imageNamed:@"RadioChecked"] forState:UIControlStateNormal];
    }else{

        [cell.answer3 setImage:[UIImage imageNamed:@"RadioUnChecked"] forState:UIControlStateNormal];
    }
    if (cell.answer4.tag==btn.tag)
    {
        NSLog(@"%ld",(long)btn.tag);
        [cell.answer4 setImage:[UIImage imageNamed:@"RadioChecked"] forState:UIControlStateNormal];
    }else{

        [cell.answer4 setImage:[UIImage imageNamed:@"RadioUnChecked"] forState:UIControlStateNormal];
    }
 }

1 个答案:

答案 0 :(得分:4)

您需要在数据源阵列中添加一个键,并根据点击操作的按钮状态修改该键值。请查看以下代码以供参考

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
        MyCustomTableViewCell *cell = (MyCustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"MyCustomTableViewCell"];
        [cell.btnSelect addTarget:self action:@selector(btnSelectClick:) forControlEvents:UIControlEventTouchUpInside];
        cell.btnSelect.selected = [[[self.arraySource objectAtIndex:indexPath.row] valueForKey:@"isSleected"] boolValue];
        cell.btnSelect.tag = indexPath.row;
        return cell;
    }
    - (void)btnSelectClick:(UIButton *)sender {
        sender.selected = !sender.selected;
        NSMutableDictionary *dicTemp = [NSMutableDictionary dictionaryWithDictionary:[self.arraySource objectAtIndex:sender.tag]];
        [dicTemp setValue:[NSNumber numberWithBool:sender.selected] forKey:@"isSleected"];
        [self.arraySource replaceObjectAtIndex:sender.tag withObject:dicTemp];
    }

  Here is arraySource in view did load
  self.arraySource = [NSMutableArray array];
  [self.arraySource addObject:@{@"name":@"name-1"}];
  [self.arraySource addObject:@{@"name":@"name-2"}];
  [self.arraySource addObject:@{@"name":@"name-3"}];