【问题标题】:Programmatically selecting a segment in UISegmentedControl based on title of that segment根据段的标题以编程方式在 UISegmentedControl 中选择段
【发布时间】:2013-05-24 22:16:29
【问题描述】:

我有一个UISegmentedControl 有几个段,每个段都有不同的“标题”。我希望能够读取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 以某种方式添加我希望它拥有的方法。不过,我讨厌这样的子类化,因为我必须去重新声明我所有的细分和其他类似的不方便的事情。但这可能是唯一的出路……


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

【问题讨论】:

    标签: objective-c uisegmentedcontrol


    【解决方案1】:

    所以当我输入这个问题时,我一直在搜索并意识到我从 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
    }
    

    这仍然感觉有点老套,并且可能违反了某处的最佳实践指南,但如果标题列表有限并且您可以确定 stringToMatch 将始终在该列表中,我认为它应该是很好。

    【讨论】:

      猜你喜欢
      • 2012-07-23
      • 2014-02-18
      • 2012-05-17
      • 2014-06-20
      • 1970-01-01
      • 2021-07-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多