iOS 开发之UILable的常见属性

2017-05-27  本文已影响16人  WuNai

UILable的常见属性

UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 120, 320, 30)];
label.text = @"文本内容文本内容文本内容";
label.attributedText = [[NSAttributedString alloc]initWithString:@"属性文本属性文本"];
label.font = [UIFont systemFontOfSize:15.0f];
label.textColor = [UIColor blackColor];
//文本的在文本框的显示位置
label.textAlignment = NSTextAlignmentLeft;
//文字过长时的现实方式
label.lineBreakMode = NSLineBreakByWordWrapping;
//文本框是否允许多行(布局相关)
label.numberOfLines = 0;
//设置是否是高亮
label.highlighted=YES;
//高亮颜色
label.highlightedTextColor=[UIColor redColor];
//设置阴影颜色
label.shadowColor=[UIColor blueColor];
//阴影偏移量
label.shadowOffset=CGSizeMake(0.5, 0.5);

其中大多数属性都是非常容易理解的。这里简单提一下其中的几个属性的枚举值。

NSTextAlignment

NSTextAlignmentLeft //左对齐
NSTextAlignmentCenter //居中
NSTextAlignmentRight //右对齐
NSTextAlignmentJustified//最后一行自然对齐
NSTextAlignmentNatural //默认对齐脚本
NSLineBreakMode
NSLineBreakByWordWrapping = 0,//以空格为边界,保留单词
NSLineBreakByCharWrapping, //保留整个字符
NSLineBreakByClipping, //简单剪裁,到边界为止
NSLineBreakByTruncatingHead, //按照"……文字"显示
NSLineBreakByTruncatingTail, //按照"文字……文字"显示
NSLineBreakByTruncatingMiddle //按照"文字……"显示
通过文本内容与字体,计算文本的所需宽高
 UILabel *label3 = [[UILabel alloc]init];
    label3.backgroundColor = [UIColor yellowColor];
    label3.font = [UIFont systemFontOfSize:17.0f];
    label3.text = @"根据文本框内容及字体,计算所需宽高";
    label3.numberOfLines = 0;
    //==================================================================================================================
    NSDictionary *attributeDic = @{NSFontAttributeName: [UIFont systemFontOfSize:17.0f]};
    CGSize constraintSize = CGSizeMake(100, CGFLOAT_MAX);
    CGSize realSize = [label3.text boundingRectWithSize:constraintSize 
                                                options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading  
                                             attributes:attributeDic 
                                                context:nil].size;

    [label3 setFrame:CGRectMake(10, 310, realSize.width, realSize.height)];
    //==================================================================================================================
    [self.view addSubview:label3];
上面的代码中,我们使用了下面的这个方法。
(CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(NSDictionary *)attributes context:(NSStringDrawingContext *)context
上一篇下一篇

猜你喜欢

热点阅读