Segmented Control set attributed title in each segment

旧巷老猫 提交于 2019-12-05 02:06:37

问题


Actually i have a segmented control with 4 segment. I need to add attributed text in each segment like "Notification (2)". Here (2) will be in different color and Notification will be in different color.

I have search some third party library , But it doesn't work for me

Thanks & Regards


回答1:


There is limitation to use attributed text as we use for label or button. But you may try below method to achieve your requirements.

-(void)SetSegmentValue:(NSString *)value forSegment:(int)index RangeOfBlueColor:(NSRange)bluecolorRange{

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:value];
NSMutableParagraphStyle *paragrahStyle = [[NSMutableParagraphStyle defaultParagraphStyle]mutableCopy];
[paragrahStyle setAlignment:NSTextAlignmentCenter];
[paragrahStyle setLineBreakMode:NSLineBreakByWordWrapping];

[attributedString addAttribute:NSParagraphStyleAttributeName value:paragrahStyle range:NSMakeRange(0, value.length)];
[attributedString addAttribute:NSForegroundColorAttributeName
                         value:[UIColor blackColor]
                         range:NSMakeRange(0, value.length)];
[attributedString addAttribute:NSForegroundColorAttributeName
                         value:[UIColor blueColor]
                         range:bluecolorRange];
[attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13.0] range:NSMakeRange(0, value.length)];

int i =0 ;
for (UIView *v in [[[segment subviews] objectAtIndex:0] subviews]) {
    if ([v isKindOfClass:[UILabel class]]&& i== index) {
        UILabel *label=(UILabel *)v ;
        [label setAttributedText:attributedString];
        i++;
        }
    }


}

NOTE : You have to modified some part of code as it's just suggestion to solve your problem



来源:https://stackoverflow.com/questions/30588196/segmented-control-set-attributed-title-in-each-segment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!