如何使用 SegmentControl ios 将数据添加到最后选择的默认索引

How to add data to last selected and default index using SegmentControl ios

我正在使用段控制。 它包含两个数据。一个数据是默认的,我需要在段中显示默认值。

我正在这样设置默认数据:

- (void)awakeFromNib 
{
    [super awakeFromNib];
    [priceOptionSeg addTarget:self action:@selector(segmentedControlValueDidChange:) forControlEvents: UIControlEventValueChanged];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated 
{
    [super setSelected:selected animated:animated];
    [self assignDO:priceList];
}

- (void)assignDO:(NSMutableArray *)inputList 
{
    for (int x = 0; x < inputList.count; x++) 
    {
        if (tempDO.price_is_default == YES) 
        {
            [priceOptionSeg setSelectedSegmentIndex:x];
            NSLog(@"%ld",(long) priceOptionSeg.selectedSegmentIndex);
        }
    }
}

我是这样管理索引的:

- (void)segmentedControlValueDidChange:(UISegmentedControl *)segment
{
    switch (segment.selectedSegmentIndex) 
    {
        case 0:
            NSLog(@"First was selected");
            break;

        case 1:
            NSLog(@"Second was selected");
            break;

        default:
            break;
    }
}

我可以在段控件中添加默认值。 我可以更改段中的值。 假设我 select 第二段 但是当我移动到下一个控制器并回到我的控制器段时,首先 index.i 想要像我移动到下一个控制器但是当我来到我的控制器时。最后 selected 段应该在那里 做什么

在你的 ViewController.h 中声明了 int like

@property(nonatomic,assign)int selectedIndex;

ViewDidLoad赋默认值

self.selectedIndex = 0;

CellForRowAtIndexpath中选择的索引

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //Create you custom class cell here
    ..
    [cell.priceOptionSeg addTarget:self action:@selector(segmentedControlValueDidChange:) forControlEvents: UIControlEventValueChanged];
    [cell.priceOptionSeg setSelectedSegmentIndex:self.selectedIndex];
    ..
}

并在同一视图控制器中添加段的值更改操作

- (void)segmentedControlValueDidChange:(UISegmentedControl *)segment
{
    switch (segment.selectedSegmentIndex) 
    {
        case 0:
            self.selectedIndex = 0;
            break;

        case 1:
            self.selectedIndex = 1;
            break;

        default:
            break;
    }
}

从您现有的 Cell 子类中删除以下行

[priceOptionSeg addTarget:self action:@selector(segmentedControlValueDidChange:) forControlEvents: UIControlEventValueChanged];