0

首先对不起标题。

我的应用程序中有一个段控件。段的标题从服务器获取并进行相应设置(即是和否)。

每个段也有一个对应的 id 值。因此,当用户选择 YES 时,将保存相应的 id 8,当用户选择 NO 时,将保存相应的 id 5(8 和 5 来自服务器)。

我尝试通过设置标签但徒劳无功。

谁能帮我解决这个问题。

提前非常感谢。

 //Code
     for(WTMobileDataService_DataAccess_ClsYesNo *temp in YesNo)
        {
            NSString *s = [NSString stringWithFormat:@"%@",temp.m_YesNoDescription];
             ind = [temp.m_PK_YesNoID intValue] - 1;

            [items addObject:s];
            [serverids addObject:[NSString stringWithFormat:@"%d",ind]];

           // [segmentControl setTitle:s forSegmentAtIndex:ind];
        }

segmentControl  = [[UISegmentedControl alloc]initWithItems:items];
4

3 回答 3

0

我很想创建一个对象来将这两个值保存在一起,因为它们看起来像是一个自然分组

@interface SegmentInfo : NSObject

@property (nonatomic, copy)  NSString  *title;
@property (nonatomic, assign NSInteger  value;

- (instancetype)initWithTitle:(NSString *)title value:(NSInteger)value;

@end

@implementation SegmentInfo

- (instancetype)initWithTitle:(NSString *)title value:(NSInteger)value
{
  self = [super init];
  if (self) {
    _title = [title copy];
    _value = value;
  }
  return self;
}

@end

现在您填充这些对象并将它们存储在一个数组中

self.segmentInfos = @[
  [[SegmentInfo alloc] initWithTitle:@"Yes" value:8],
  [[SegmentInfo alloc] initWithTitle:@"No"  value:5],
];

要设置分段控件,您只需将所有标题抓取到一个数组中

some set up method
{
  NSArray *segmentTitle = [self.segmentInfo valueForKey:@"title"];
  self.segmentControl   = [[UISegmentedControl alloc] initWithItems:segmentTitle];
}

现在在处理值更改的方法中,您只需在同一索引处抓取对象并获取值

- (IBAction)segmentedControlChanged:(UISegmentedControl *)segmentedControl
{
  SegmentInfo *selectedSegment = self.segmentInfos[segmentedControl.selectedSegmentIndex];
  NSLog(@"title: %@, value: %d", selectedSegment.title, selectedSegment.value);
}
于 2013-04-10T22:34:57.367 回答
0

有两个数组,一个带有标题,另一个带有值。当用户选择一个段时,使用选择的段返回标题,然后用它来获取标题的索引。然后你可以引用 values 数组,你就得到了相应的值。

您也可以使用 NSDictionary 来实现相同的目的,其中标题是您的键,值是......值。

像这样的东西:

NSArray titles = @[@"YES", @"NO"];
NSArray values = @[8, 5];

UISegmentedControl control; // Likely defined as a property
if ([control selectedSegmentIndex] != UISegmentedControlNoSegment) {
    NSString title = [control titleForSegmentAtIndex:];

    int index = [titles indexOfObject:title];
    NSString value = [values objectAtIndex:index];
}
于 2013-04-10T16:20:58.703 回答
0

由于每个UISegmentedControl标签只有一个标签,因此您需要执行以下操作:

NSMutableArray *items = [NSMutableArray new];
NSMutableArray *serverIds = [NSMutableArray new];

for (ServerResponseObject *response in serverResponses) {
    [items addObject:response.title];
    [serverIds addObject:response.id];
}

mySegmentedControl = [[UISegmentedControl alloc] initWithItems:items];

此后,当用户点击 时UISegmentedControl,访问selectedIndex分段控件的属性以找出他们点击了哪个分段,并使用该值作为serverIds数组的键,根据服务器查看对应的 ID 号是多少。

于 2013-04-10T16:22:37.093 回答