Search code examples
iosobjective-cnsarrayuisegmentedcontrolfor-in-loop

Add segments from a UISegmentedControl to an NSArray


I'm trying to add 2 segments to an array, then loop through its subviews. Here is my code:

NSArray *myArray = [[NSArray alloc] initWithObjects:[self.segment.subviews objectAtIndex:0],
                                   [self.dataSegmentedControl.subviews objectAtIndex:1], nil];


for (id innerView in myArray) // I tried "myArray.subviews" but it didn't let me do ".subviews"
{
    if ([innerView isKindOfClass:[UILabel class]]) {
        ...
    }
}

When I insert an NSLog in the if statement, I don't get any output. What can I do to fix that?:


Solution

  • There are only two possible reasons for what you see:

    1. None of the array's elements is a UILabel
    2. There are no elements in the array. This could be because [self.segment.subviews objectAtIndex:0] returns nil, which only means that the self.segment is nil.

    Try to explore the view hierarchy, before you assume anything. So print out the segments and their subviews to know the hierarchy.

    However, if you want to change the font size of some segments but not the others, I'd recommend not to go this way and mess with the internal structure. If it worked out, you should expect a problem with any upcoming system update. I suggest you search for other 3rd party components or build your own.