Formatting UILabel - bold and color

There are different options to format a text in an iOS app. If you want to place it inside an UILabel, a solution is to use the following code: UILabel+Bold_Color.h

#import <UIKit/UIKit.h>
@interface UILabel (Bold_Color)
- (void)boldSubstring:(NSString*)substring;
- (void)boldRange:(NSRange)range;
- (void)boldAndColorSubstring:(NSString*)substring forColor:(UIColor *)color;
- (void)boldAndColorRange:(NSRange)range forColor:(UIColor *)color;
@end

UILabel+Bold_Color.m

#import "UILabel+Boldify.h"
@implementation UILabel (Bold_Color)
- (void)boldRange:(NSRange)range {
    if (![self respondsToSelector:@selector(setAttributedText:)]) {
        return;
    }
    NSMutableAttributedString *attributedText;
    if (!self.attributedText) {
        attributedText = [[NSMutableAttributedString alloc] initWithString:self.text];
    } else {
        attributedText = [[NSMutableAttributedString alloc]initWithAttributedString:self.attributedText];
    }
    [attributedText setAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:self.font.pointSize]} range:range];
    self.attributedText = attributedText;
}
- (void)boldSubstring:(NSString*)substring {
    NSRange range = [self.text rangeOfString:substring];
    [self boldRange:range];
}
- (void)boldAndColorRange:(NSRange)range forColor:(UIColor *)color {
    if (![self respondsToSelector:@selector(setAttributedText:)]) {
        return;
    }
    NSMutableAttributedString *attributedText;
    if (!self.attributedText) {
        attributedText = [[NSMutableAttributedString alloc] initWithString:self.text];
    } else {
        attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    }
    [attributedText setAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:self.font.pointSize], NSForegroundColorAttributeName:color} range:range];
    self.attributedText = attributedText;
}
- (void)boldAndColorSubstring:(NSString*)substring forColor:(UIColor *)color {
    NSRange range = [self.text rangeOfString:substring];
    [self boldAndColorRange:range forColor:color];
}
@end

Then when you want to format bold "myText" from UILabel text:

[myLabel boldSubstring:[NSString stringWithFormat:@"%d", @"myText"]];

or set bold and blue color:

[myLabel boldAndColorSubstring:[NSString stringWithFormat:@"%d", @"myText"] forColor:[UIColor blueColor]];

Categories

Archive