Bold & Non-Bold Text In A Single UILabel?

后端 未结 14 2432
别那么骄傲
别那么骄傲 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 09:27

    Try a category on UILabel:

    Here's how it's used:

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

    And here's the category

    UILabel+Boldify.h

    - (void) boldSubstring: (NSString*) substring;
    - (void) boldRange: (NSRange) range;
    

    UILabel+Boldify.m

    - (void) boldRange: (NSRange) range {
        if (![self respondsToSelector:@selector(setAttributedText:)]) {
            return;
        }
        NSMutableAttributedString *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];
    }
    

    Note that this will only work in iOS 6 and later. It will simply be ignored in iOS 5 and earlier.

提交回复
热议问题