我最近正在学习iOS开发,我想知道是否可以有一个不同大小,不同字体和不同颜色的标签,例如
用户名(蓝色,大胆,大字体)正在 xxxx网站上观看行尸走肉(红色,大胆和中等字体)(蓝色,大胆和大字体)谢谢!
答案 0 :(得分:4)
有两种方法可以做到这一点
xib文件或故事板
去标签,选择属性而不是普通
然后在那里做你想做的事码
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
我个人更喜欢第二种解决方案,因为您在代码中有更多选项,并且几乎适用于所有情况。但是有一个学习曲线。
希望有所帮助
答案 1 :(得分:0)
在您的情况下,您需要使用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
进行精简: