在iOS7中的SegmentController中选择了多个段

时间:2014-01-03 11:18:37

标签: objective-c ios7 uisegmentedcontrol

我在 CellForRowAtIndex 方法中添加了一个 SegementController ,以及我们之前选择的选定持续值。但是一旦我们转移到其他屏幕并回到当前状态,Segement将会选择多个选项,如下所示:

enter image description here

此处已选择“是”,然后我选择“否”,

这是我在CellForRowAtIndexPath中编写的代码:

   UISegmentedControl *seg = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"Yes", @"No", @"Either", nil]];
   seg.frame = CGRectMake(190.0f, 10.0f, 205.0f, 30.0f);
   seg.selectedSegmentIndex = 0;
   [seg setTintColor:[UIColor orangeColor]];
   seg.segmentedControlStyle = UISegmentedControlStyleBar;
   [seg addTarget:self action:@selector(segSelected:) forControlEvents:UIControlEventValueChanged];
   seg.tag = indexPath.row;
   cell.textLabel.frame = CGRectMake(10, 5, 150, 30);
   [cell.contentView addSubview:seg];
   seg.selectedSegmentIndex = [[[arryaSegment objectAtIndex:indexPath.row]objectForKey:@"SelecteKey"] intValue];

1 个答案:

答案 0 :(得分:3)

这可能不是同时选择2个段,而是同时添加两个segmentedControl,因为每次显示单元格时都会添加一个新控件。

确保每个单元格只调用一次添加UISegmentedControl的代码。

e.g:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell; // = ... dequeue ...
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];

        // add segmented control only when creating a new cell
        UISegmentedControl *seg = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"Yes", @"No", @"Either", nil]];
        seg.frame = CGRectMake(190.0f, 10.0f, 205.0f, 30.0f);
        seg.selectedSegmentIndex = 0;
        [seg setTintColor:[UIColor orangeColor]];
        seg.segmentedControlStyle = UISegmentedControlStyleBar;
        [seg addTarget:self action:@selector(segSelected:) forControlEvents:UIControlEventValueChanged];
        cell.textLabel.frame = CGRectMake(10, 5, 150, 30);
        [cell.contentView addSubview:seg];

        seg.tag = 42; // used to reference segmentedControl in dequeued cell. see next line
    }

    UISegmentedControl *seg = (UISegmentedControl *)[cell.contentView viewWithTag:42];
    seg.selectedSegmentIndex = [[[arryaSegment objectAtIndex:indexPath.row]objectForKey:@"SelecteKey"] intValue];

    return cell;
}

因为你不能再使用带有segmentedControl标记的indexPath的丑陋方式,你必须使用一种以不同方式获取indexPath的方法。像这样:

- (IBAction)segSelected:(UISegmentedControl *)sender {
    CGPoint originOfSegmentedControlInTableView = [sender convertPoint:CGPointZero toView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:originOfSegmentedControlInTableView];
    ...
}