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

标签 ios objective-c uisegmentedcontrol

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

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

- (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;
    }
}

我可以在段控制中添加默认值。 我可以更改段中的值。 假设我选择第二段 但是当我移动到下一个 Controller 并回到我的 Controller 段时,首先是索引。我想如果我移动到下一个 Controller 但是当我来到我的 Controller 时。最后选择的段应该在那里 做什么

最佳答案

在你的 ViewController.h 中声明了 int 之类的

@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];
    ..
}

并在同一个view controller中添加segment的value change action

- (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];

关于ios - 如何使用 SegmentControl ios 将数据添加到最后选择的索引和默认索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40801495/

相关文章:

ios - 使用 resizableImageWithCapInsets 自定义 UISegmentedControl

php - 将方法 nsdictionary 发布到 json 对象 iOS objective-c

ios - 如何重新创建 iOS 7 Weather App View Controller 转换

iOS 8 UIImagePickerController 只拍照片的照片

xcode - 如何在 Swift 中突出显示分段控制中最后触摸的段?

swift - 如何快速自定义 UISegmentedControl 的边框

ios - 将用户的文本输入限制在 UITextView 的高度

c# - MonoTouch 中的 ViewForZoomingInScrollView

objective-c - 切成字符串

objective-c - 将方向更改为横向后,uiwebview 未调整大小