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 = [[NSString alloc] initWithFormat:_deviceSegmentCntrl];

我想让 NSString 输出用户在分段控件中选择的字符串。

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

干杯

4

3 回答 3

2

Firstly, NSString's are so common that there is a shorthand to greatly simplify your instantiations:

deviceOne = @"string01";

is has an identical result to

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

Now, I'm not sure exactly what you are wanting to achieve, so I'll mention a few things that I think are in the ballpark.

If you just want a string that is exactly what is displayed on the control, use

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

When you want a more complex string, you can use the class method stringWithFormat, perhaps like this:

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

Where deviceOne is from your posted code.

于 2012-06-23T21:08:01.597 回答
0

听起来您想要以下内容:

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

假设您的分段控件只有三个选项 - 根据所选索引,deviceType 将是字符串“0”、“1”或“2”的 NSString 变量。

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

根据您的评论进行编辑-

如果要在 deviceType 字符串中包含 deviceOne 字符串,则可以执行以下操作:

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

或者,如果您想要选择的分段控制按钮中的文本,那么以下内容将对您有所帮助。

int myIndex = _deviceSegmentCntrl.selectedSegmentIndex;
NSString *segmentString = [_deviceSegmentCntrl titleForSegmentAtIndex:myIndex];
NSString *deviceType = [[NSString alloc] initWithFormat:@"%@",segmentString];
于 2012-06-23T21:05:20.943 回答
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;

is this what you're trying to do? Just display the string you created? Why do you even need the deviceType string if that is the case?

于 2012-06-23T21:12:10.203 回答