Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create multi line UISegmentedControl?

I have a relative longer text items in my segmented control so I need to break text at certain points. Is it possible to use line breaks? I know at buttons I need to set line break to word wrap, but how to to set it for UISegmentedControl.

like image 473
János Avatar asked Jan 19 '15 15:01

János


3 Answers

Please refer to this answer

Swift 3+

UILabel.appearance(whenContainedInInstancesOf: [UISegmentedControl.self]).numberOfLines = 0

Objective C

[[UILabel appearanceWhenContainedIn:[UISegmentedControl class], nil] setNumberOfLines:0];
like image 55
Maverick Avatar answered Nov 12 '22 08:11

Maverick


if you have a standard UISegmentedControl you can use the following idea:

[_segmentedControl.subviews enumerateObjectsUsingBlock:^(UIView * obj, NSUInteger idx, BOOL *stop) {
    [obj.subviews enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if ([obj isKindOfClass:[UILabel class]]) {
            UILabel *_tempLabel = (UILabel *)obj;
            [_tempLabel setNumberOfLines:0];
        }
    }];     
}];

you may need to set the height of your instance as well.


NOTE: I need to add a little warning about – as rmaddy has also pointed out correctly – this is a quite fragile solution, because if the segmented control's view hierarchy would be changed in the future iOS versions that code may not work properly anymore.

like image 4
holex Avatar answered Nov 12 '22 08:11

holex


Swift 4 version of solution. segmentedControl is your instance of UISegmentedControl.

        for segmentItem : UIView in segmentedControl.subviews
    {
        for item : Any in segmentItem.subviews {
            if let i = item as? UILabel {
                i.numberOfLines = 0
                // change other parameters: color, font, height ... 
            }
        }
    }

Don't forget to set segmentedControl's height as a doubled font's height.

like image 2
Agisight Avatar answered Nov 12 '22 08:11

Agisight