1

我有UISegmentedControl几个段,每个段都有不同的“标题”。我希望能够读取 a NSString,并以编程方式选择标题与该字符串匹配的段。假设我从以下内容开始:

NSString *stringToMatch = @"foo";
UISegmentedControl *seg = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"foo",@"bar",@"baz", nil]];

我想做类似的事情:

[seg selectSegmentWithTitle:stringToMatch];

但是由于没有调用方法selectSegmentWithTitle,所以这不起作用。有人知道与此类似的方法吗?


我还想过循环遍历 中的所有标题seg,类似于:

int i = 0;
for (UISegment *thisSeg in [seg allSegmentsInOrder])
{
    if ([thisSeg.title isEqualToString:stringToMatch])
    {
        [seg setSelectedSegmentIndex:i];
        break;
    }
    i++;
}

但据我所知,没有这样的东西UISegment,也没有方法allSegmentsInOrder。再说一次,有人知道我可以做些什么改变来让它工作吗?


第三,我可能可以继承 UISegmentedControl 以某种方式添加我希望它拥有的方法。不过,我讨厌这样的子类化,因为我必须去重新声明我所有的细分和其他类似的不方便的事情。但这可能是唯一的出路……


也许这样做的方式与我上面列出的三个想法完全不同。我对任何事情都持开放态度。

4

1 回答 1

2

因此,当我输入这个问题时,我一直在搜索并意识到我从 OP 获得的第二种方法非常接近。我想我仍然应该发布我想出的东西,以防其他人将来会寻找这样的东西。

for (int i = 0; i < [seg numberOfSegments]; i++)
{
    if ([[seg titleForSegmentAtIndex:i] isEqualToString:stringToMatch])
    {
        [seg setSelectedSegmentIndex:i];
        break;
    }
    //else {Do Nothing - these are not the droi, err, segment we are looking for}
}
if ([seg selectedSegmentIndex] == -1)
{
    NSLog(@"Error - segment with title %@ not found in seg",stringToMatch);
    NSLog(@"Go back and fix your code, you forgot something");
    // prob should do other stuff here to let the user know something went wrong
}

这仍然感觉有点 hacky,并且可能与某处的一些最佳实践指南背道而驰,但如果标题列表有限并且您可以确定stringToMatch将始终在该列表中,我认为它应该没问题。

于 2013-05-23T20:16:44.397 回答