Reputation: 13
I've been trying to customize UISegmentControl to look like this:
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:
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?
Upvotes: 1
Views: 53
Reputation: 131426
Don't do that. A segmented control is intended to be used as-is. It's internal view hierarchy is private, and subject to change between OS versions. By reaching inside the control and mucking around, all bets are off. Even if you get it working today, any future OS version could break you.
If you want to customize a segmented control build it yourself from scratch. It isn't that hard. In fact it's probably gonna be easier than what you're trying to do, and certainly much safer.
Upvotes: 1
Reputation: 318824
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.
Upvotes: 1