BadPirate
BadPirate

Reputation: 26177

UIView at Index for UISegmentedControl

I would like to change the background color for a specific segment (not the selected segment) inside a UISegmentedControl, but it seems it's actually pretty difficult to grab the appropriate UIView for a specific segment. I'm looking for a method like:

[segmentedControl viewForSegmentAtIndex:3];

Upvotes: 0

Views: 229

Answers (1)

BadPirate
BadPirate

Reputation: 26177

Ended up doing it with a category :)

@interface UISegmentedControl (BP)
- (UIView *)segmentAtIndex:(NSUInteger)index;
@end

@implementation UISegmentedControl (BP)
- (UIView *)segmentAtIndex:(NSUInteger)index
{
    // All the views are a private subclass "UISegment", and are not ordered sanely, no problem, we can fix that
    return [self.subviews sortedArrayWithOptions:0 usingComparator:^NSComparisonResult(UIView *obj1, UIView *obj2) {
        return [@(obj1.frame.origin.x) compare:@(obj2.frame.origin.x)];
    }][index];
}
@end

Upvotes: 3

Related Questions