1

I have a UISegmentedControl with several segments, each with a different "title". I want to be able to read in a NSString, and programmatically select the segment whose title matches that string. Say I start with something like:

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

I want to do something like:

[seg selectSegmentWithTitle:stringToMatch];

But since there is no method called selectSegmentWithTitle, this doesn't work. Is anyone aware of a method that would be similar to this though?


I've also thought of looping over all the titles in seg, similar to this:

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

but to my knowledge there is no such thing as UISegment, nor is there a method allSegmentsInOrder. Again, does anyone know of any changes I could make to get this to work?


Thirdly, I could probably subclass UISegmentedControl to somehow add the methods I want it to have. I hate subclassing like that though, cause I'd have to go and re-declare all my segments and other inconvenient things like that. But it may be the only way to go...


Perhaps the way to do this is totally different from the three ideas I listed above. I'm open to whatever.

1 Answer 1

2

So while I was typing this question up, I kept searching and realized that my second method from OP is pretty close. I figured I should still post what I came up with, in case someone else is looks for something like this in the future.

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
}

This still feels a little hacky, and is probably against some best practice guide somewhere, but if there's a finite list of titles and you can be certain stringToMatch will always be on that list, I'm thinking it should be fine.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.