通過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);
}