Can I set the `attributedText` property of `UILabel`

后端 未结 8 892
长发绾君心
长发绾君心 2020-12-22 21:52

Can I set the attributedText property of a UILabel object? I tried the below code:

UILabel *label = [[UILabel alloc] init];
label.a         


        
8条回答
  •  春和景丽
    2020-12-22 22:15

    NSString *str1 = @"Hi Hello, this is plain text in red";
    
    NSString *cardName = @"This is bold text in blue";
    
    NSString *text = [NSString stringWithFormat:@"%@\n%@",str1,cardName];
    
    
    // Define general attributes for the entire text
    NSDictionary *attribs = @{
                              NSForegroundColorAttributeName:[UIColor redColor],
                              NSFontAttributeName: [UIFont fontWithName:@"Helvetica" size:12]
                              };
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text attributes:attribs];
    
    
    UIFont *boldFont = [UIFont fontWithName:@"Helvetica-Bold" size:14.0];
    NSRange range = [text rangeOfString:cardName];
    [attributedText setAttributes:@{NSForegroundColorAttributeName: [UIColor blueColor],
                                    NSFontAttributeName:boldFont} range:range];
    
    
    myLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    
    myLabel.attributedText = attributedText;
    

提交回复
热议问题