【问题标题】:Have different color and different font size in one label [duplicate]在一个标签中具有不同的颜色和不同的字体大小[重复]
【发布时间】:2014-02-07 13:28:16
【问题描述】:

我最近在学习iOS开发,我想知道是否可以有一个不同大小、不同字体和不同颜色的标签,例如

用户名(蓝色,加粗,大字体)正在观看行尸走肉(红色,加粗和中等字体)xxxx网站(蓝色,加粗和大字体)

谢谢!

【问题讨论】:

标签: ios uilabel


【解决方案1】:

有两种方法可以做到这一点

  1. xib 文件或情节提要

    去标签,选择属性而不是普通的

    然后在那里做任何你想做的事

  2. 代码

    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:@"user name is watching walking dead on xxx site"];
    
        [attributedString addAttributes:[[NSDictionary alloc] initWithObjectsAndKeys:
                                        NSFontAttributeName, [UIFont fontWithName:@"WHATEVER FONT" size:FONT_SIZE_HERE],
                                        NSForegroundColorAttributeName, [UIColor blueColor],
                                        nil]
                          range:NSMakeRange(0, 9)];//9 is the length of "user name"
    
        [attributedString addAttributes:[[NSDictionary alloc] initWithObjectsAndKeys:
                                 NSFontAttributeName, [UIFont fontWithName:@"WHATEVER FONT" size:FONT_SIZE_HERE],
                                 NSForegroundColorAttributeName, [UIColor blueColor],
                                 nil]
                          range:NSMakeRange(22, 12)];//22 is the start index of "Walking dead"
                                                     //and 12 is the length of "Walking dead"
    
    //you got the idea, same way to do the xxx site.
    //Check a file called "NSAttributedString.h" 
    //you will find even more options there
    

我个人更喜欢第二种解决方案,因为您在代码中有更多选项,并且几乎适用于所有情况。但是有一个学习曲线。

希望有帮助

【讨论】:

    【解决方案2】:

    在您的情况下,您需要使用NSMutableAttributedString.

    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString: @"monkey goat"];        
    UILabel *testingLbl = [[UILabel alloc] init];
    testingLbl.frame = CGRectMake(50, 100, 200, 30);
    [attString addAttribute: NSForegroundColorAttributeName value: [UIColor redColor] range: NSMakeRange(0,6)];                
    [attString addAttribute: NSFontAttributeName value:  [UIFont fontWithName:@"Helvetica" size:15] range: NSMakeRange(0,6)];        
    [attString addAttribute: NSFontAttributeName value:  [UIFont fontWithName:@"Didot" size:24] range: NSMakeRange(7,4)];        
    testingLbl.attributedText  = attString;
    [self.view addSubview:testingLbl];
    

    这也是查找任何自定义控制器的最佳站点,再见,在您的情况下很好 UILabel 源代码:

    【讨论】:

      猜你喜欢
      • 2016-04-21
      • 1970-01-01
      • 1970-01-01
      • 2017-11-28
      • 2021-01-02
      • 2022-11-03
      • 2012-11-14
      • 1970-01-01
      • 2014-08-28
      相关资源
      最近更新 更多