UILabel 的操作在APP开发中属于最基础的组成成分。然而它的一些基础属性只有在用到时才会发现前人的抽象思维之细腻,你用于不用,他就在那里!
一、一个label中展示多种字体,颜色,大小。(引用链接)
NSMutableAttributedString* str = [[NSMutableAttributedStringalloc]initWithString:@"Using NSAttributed String"];
[str addAttribute:NSForegroundColorAttributeNamevalue:[UIColor blueColor]range:NSMakeRange(0,5)];
[str addAttribute:NSForegroundColorAttributeNamevalue:[UIColor redColor]range:NSMakeRange(6,12)];
[str addAttribute:NSForegroundColorAttributeNamevalue:[UIColor greenColor]range:NSMakeRange(19,6)];
[str addAttribute:NSFontAttributeNamevalue:[UIFont fontWithName:@"Arial-BoldItalicMT"size:15.0]range:NSMakeRange(0,5)];
[str addAttribute:NSFontAttributeNamevalue:[UIFont fontWithName:@"HelveticaNeue-Bold"size:20.0]range:NSMakeRange(6,12)];
[str addAttribute:NSFontAttributeNamevalue:[UIFont fontWithName:@"Courier-BoldOblique"size:10.0]range:NSMakeRange(19,6)];
UILabel* label = [[UILabel alloc] initWithFrame: aFrame];
label.attributedText= str;
PS:另一种常用方法(本方法只适用于类似下图情况)
+ (NSMutableAttributedString*)setAllText:(NSString*)allStrandSpcifiStr:(NSString*)specifiStrwithColor:(UIColor*)colorspecifiStrFont:(UIFont*)font {
NSMutableAttributedString*mutableAttributedStr = [[NSMutableAttributedStringalloc]initWithString:allStr];
if(color ==nil) {
color = [UIColorredColor];
}
if(font ==nil) {
font = [UIFontsystemFontOfSize:17.];
}
// NSArray *array = [allStr componentsSeparatedByString:specifiStr];//array.cout-1是所有字符特殊字符出现的次数
NSRange searchRange = NSMakeRange(0, [allStrlength]);
NSRange range;
//拿到所有的相同字符的range
while
((range = [allStrrangeOfString:specifiStroptions:0range:searchRange]).location!= NSNotFound) {
//改变多次搜索时searchRange的位置
searchRange = NSMakeRange(NSMaxRange(range), [allStrlength] - NSMaxRange(range));
//设置富文本
[mutableAttributedStraddAttribute:NSForegroundColorAttributeNamevalue:colorrange:range];
[mutableAttributedStraddAttribute:NSFontAttributeNamevalue:fontrange:range];
}
returnmutableAttributedStr;
}
二、已知展示文字内容,字体大小,求label的展示宽度。(一般用于单行文字,多行应该也可以,不常用)
NSString* aStr =@"hello world!";
NSInteger aStrFontSzie =14;
CGSize aStrSize = [aStr sizeWithAttributes:@{ NSFontAttributeName : [UIFont systemFontOfSize:aStrFontSzie] }];
三、label 在TableView上的,table是可移动的。求某一时刻此label相对屏幕(self.view)的坐标。(一般用于在此处加盖一层View的操作)
UILabel* label = [[UILabel alloc]initWithFrame:aFrame];
CGRect labelNewFrame = [label convertRect: label.bounds toView:self.view];