1. 程式人生 > >同一個label顯示不同的字型大小和字型顏色

同一個label顯示不同的字型大小和字型顏色

UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 100, 320, 40)];
[self.view addSubview:label];

//指定位置
NSMutableAttributedString *str1 = [[NSMutableAttributedString alloc] initWithString:@"點選代表您已閱讀並同意使用者規則和協議"];
[str1 addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(0,11)];
[str1 addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(11,4)];
[str1 addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(16,2)];
label.attributedText = str1;


//指定字型
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"點選代表您已閱讀並同意使用者規則和協議"];
NSRange range1 = [[str string] rangeOfString:@"點選代表您已閱讀並同意"];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:range1];
[str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13] range:range1];
NSRange range2 = [[str string] rangeOfString:@"使用者規則"];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range2];
[str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:range2];
NSRange range3 = [[str string] rangeOfString:@"協議"];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:range3];
[str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:range3];
label.attributedText = str;


//設定字型大小
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"set background color with button"];
[string addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldItalicMT" size:17.0] range:NSMakeRange(0, 5)];
[string addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:17.0] range:NSMakeRange(6, 12)];
[string addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Courier-BoldOblique" size:17.0] range:NSMakeRange(19, 6)];