stackques tion stackques tion - 2 months ago 15
iOS Question

uisegment control with diff text size

I've been trying to customize UISegmentControl to look like this:

enter image description here

First I loop through the labels in UISegmentControl and set each to multiline, but when I try to alter the label text attributes it doesn't change the font. I tried using this attribute on a normal UILabel and it works, but not within uisegment

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

NSMutableAttributedString *attString =
[[NSMutableAttributedString alloc]
initWithString: @"monkey goat"];

[attString addAttribute: NSForegroundColorAttributeName
value: [UIColor redColor]
range: NSMakeRange(0,6)];


[attString addAttribute: NSFontAttributeName
value: [UIFont fontWithName:@"Helvetica" size:15]
range: NSMakeRange(0,6)];

[attString addAttribute: NSFontAttributeName
value: [UIFont fontWithName:@"Didot" size:24]
range: NSMakeRange(7,4)];

_tempLabel.attributedText = attString;
}
}];
}];


This is the result:

enter image description here

Changing label attribute attached to view works:

NSMutableAttributedString *attString =
[[NSMutableAttributedString alloc]
initWithString: @"monkey goat"];

[attString addAttribute: NSForegroundColorAttributeName
value: [UIColor redColor]
range: NSMakeRange(0,6)];


[attString addAttribute: NSFontAttributeName
value: [UIFont fontWithName:@"Helvetica" size:15]
range: NSMakeRange(0,6)];

[attString addAttribute: NSFontAttributeName
value: [UIFont fontWithName:@"Didot" size:24]
range: NSMakeRange(7,4)];

self.label.attributedText = attString;


SO links to change label attribute: Different font size in the same label?

Answer

UISegmentedControl does not support what you are trying to do. The API only supports setting a single font for all of the segment's titles by using the 'setTitleTextAttributes:forState:` method.

Ultimately, the segmented control will reset whatever attributes you might set after digging through the private subviews. It'a never a good idea to fight an API nor is it ever a good idea to dig into a view's undocumented subviews. Such solutions may work at times but most are doomed to break when a future iOS update is available.

Your only option is to create your own custom control that does what you want or find one created by someone else.

Comments