当前位置: 代码迷 >> 综合 >> iOS开发笔记 如何渲染自定义格式字符串的UILabel
  详细解决方案

iOS开发笔记 如何渲染自定义格式字符串的UILabel

热度:127   发布时间:2023-10-17 13:10:52.0

通过NSMutableAttributedString设置, 代码如下

- (void)viewDidLoad  
{  [super viewDidLoad];  NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"欢迎来到晟楠的博客"];  // 设置文字颜色  [str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, 1)];//第一个文字显示蓝色  [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(7, 2)];/最后两个文字显示红色  // 设置字体  [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30] range:NSMakeRange(1, 3)];  self.label.attributedText = str;  //在viewdidload方法中,view刚刚创建,可能并不是真正的frame,在viewdidload中设置contentsize不太好  self.scrollView.contentSize = CGSizeMake(1000, 400);  
}