Bold & Non-Bold Text In A Single UILabel?

后端 未结 14 2437
别那么骄傲
别那么骄傲 2020-11-22 08:51

How would it be possible to include both bold and non-bold text in a uiLabel?

I\'d rather not use a UIWebView.. I\'ve also read this may be possible using NSAttribut

14条回答
  •  日久生厌
    2020-11-22 09:32

    There's category based on bbrame's category. It works similar, but allows you boldify same UILabel multiple times with cumulative results.

    UILabel+Boldify.h

    @interface UILabel (Boldify)
    - (void) boldSubstring: (NSString*) substring;
    - (void) boldRange: (NSRange) range;
    @end
    

    UILabel+Boldify.m

    @implementation UILabel (Boldify)
    - (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];
    }
    @end
    

    With this corrections you may use it multiple times, eg:

    myLabel.text = @"Updated: 2012/10/14 21:59 PM";
    [myLabel boldSubstring: @"Updated:"];
    [myLabel boldSubstring: @"21:59 PM"];
    

    will result with: "Updated: 2012/10/14 21:59 PM".

提交回复
热议问题