2012-06-23 27 views
0

你好,我有以下代码:IOS - UISegmentedControl和的NSString

if(_deviceSegmentCntrl.selectedSegmentIndex == 0) 
{ 
    deviceOne = [[NSString alloc] initWithFormat:@"string01"]; 
} 
if(_deviceSegmentCntrl.selectedSegmentIndex == 1) 
{ 
    deviceOne = [[NSString alloc] initWithFormat:@"string02"]; 
} 
if(_deviceSegmentCntrl.selectedSegmentIndex == 2) 
{ 
    deviceOne = [[NSString alloc] initWithFormat:@"string03"]; 
} 

NSString *deviceType = [[NSString alloc] initWithFormat:_deviceSegmentCntrl]; 

我想拥有的NSString输出的用户选择分段控制的字符串。

我该如何附加initWithFormat:以便它反映所选的索引?

干杯

回答

2

首先,的NSString的是如此普遍,有一个速记,大大简化了您的实例:

deviceOne = @"string01"; 

是具有相同的结果

deviceOne = [[NSString alloc] initWithFormat:@"string01"]; 

现在,我不当然正好你想要达到什么,所以我会提到一些我认为是在大局的东西。

如果你只是想要一个字符串,它究竟是什么显示在控制,使用

NSString deviceType = [_deviceSegmentCntrl titleForSegmentAtIndex:_deviceSegmentCn.selectedSegmentIndex]; 

当你想要一个更复杂的字符串,可以使用类方法stringWithFormat,也许是这样的:

NSString *deviceType = [NSString stringWithFormat:@"%@ - %@", deviceOne, [_deviceSegmentCntrl titleForSegmentAtIndex:_deviceSegmentCn.selectedSegmentIndex]]; 

其中deviceOne来自您的发布代码。

+0

超级!!!对字符串的建议+1和工作的答案喜欢魅力:-) –

0

这听起来像你想以下几点:

int myIndex = _deviceSegmentCntrl.selectedSegmentIndex; 
NSString *deviceType = [[NSString alloc] initWithFormat:@"%d",myIndex]; 

假定你分段控制只有三个选项 - 设备类型将是字符串“0”的NSString变量,“1” ,或根据所选索引的“2”。

确保在完成使用后释放deviceType。

编辑根据您的评论 -

如果你想在你的设备类型的字符串deviceOne字符串,那么你就可以做到以下几点:

NSString *deviceType = [[NSString alloc] initWithFormat:@"%@",deviceOne]; 

另外,如果你想从文本分段的控制按钮被选中,那么以下内容将对您有所帮助。

int myIndex = _deviceSegmentCntrl.selectedSegmentIndex; 
NSString *segmentString = [_deviceSegmentCntrl titleForSegmentAtIndex:myIndex]; 
NSString *deviceType = [[NSString alloc] initWithFormat:@"%@",segmentString]; 
+0

是的,这听起来是正确的,但是这仍然输出段号而不是我声明的字符串。 –

0
if(_deviceSegmentCntrl.selectedSegmentIndex == 0) 
{ 
    deviceOne = [[NSString alloc] initWithFormat:@"string01"]; 
} 
if(_deviceSegmentCntrl.selectedSegmentIndex == 1) 
{ 
    deviceOne = [[NSString alloc] initWithFormat:@"string02"]; 
} 
if(_deviceSegmentCntrl.selectedSegmentIndex == 2) 
{ 
    deviceOne = [[NSString alloc] initWithFormat:@"string03"]; 
} 

NSString *deviceType = deviceOne; 

这是你要做的吗?只显示你创建的字符串?为什么你甚至需要deviceType字符串,如果是这样的话?