iOS开发-自定义UILabel

作者: PerhapYs | 来源:发表于2015-12-25 17:23 被阅读720次

自定义UILabel

本篇作为UILable设置的一个个人整理,以达到能满足需要的自定义.

自定义UILabel.text

1.给UILabel.text添加下划线

NSString *testStr = @"添加下划线";
NSMutableAttributedString *MAString = [[NSMutableAttributedString alloc] initWithString:testStr];

// 配置下划线
[MAString addAttributes:@{NSUnderlineStyleAttributeName:[NSNumber numberWithInteger:NSUnderlineStyleSingle]} range:NSMakeRange(0,[testStr length])]; 

UILabel *testLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
//添加配置
[testLabel setAttributedText:MAString];
[self.view addSubview:testLabel];

2.给UILabel.text的局部改变颜色

//    设置变换颜色,以及变换范围(4,7)
[MString addAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]} range:NSMakeRange(4, 7)];

3.设置窜行间距

 NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
 //    设置行间距 50
paragraphStyle.lineSpacing = 50;
//    设置段落间距
paragraphStyle.paragraphSpacing = 10;
//  两种添加办法
//    [MString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, 3)];

[MString addAttributes:@{NSParagraphStyleAttributeName:paragraphStyle} range:NSMakeRange(0, 3)];

4.设置字符间间距

//    设置字间距为4.0f
long number = 4.0f;

CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number);

[MString addAttribute:(id)kCTKernAttributeName value:(__bridge id)num range:NSMakeRange(0,[MString length])];

5.设置局部大小

[MString addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:30]} range:NSMakeRange(3, 3)];

6.设置局部背景颜色

[MString addAttributes:@{NSBackgroundColorAttributeName:[UIColor blueColor]} range:NSMakeRange(10, 5)];

7.设置局部描边颜色

//    一般与描边宽度一起使用
[MString addAttributes:@{NSStrokeColorAttributeName:[UIColor greenColor]} range:NSMakeRange(15, 7)]; 

8.设置局部描边宽度

[MString addAttributes:@{NSStrokeWidthAttributeName:@(2)} range:NSMakeRange(16, 5)];

同样地,以上方法对于UIButton也可以使用类似的配置,添加配置的方法为:

     setAttributedTitle:<#(nullable NSAttributedString *)#> forState:<#(UIControlState)#>

依据UILabel.text获取UILabel的size

这里使用UILabel.textfont = 15,width = 100,text = @"在这里计算UILabel的大小"来计算UILabel的大小。

UILabel *testLabel = [UILabel new];
// 设置无线行
testLabel.numberOfLines = 0;
NSString *testStr = @"在这里计算UILabel的大小";
testLabel.text = testStr;

//配置计算大小时,字体的大小
NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:15]};

//计算大小
CGSize userSize = [testStr boundingRectWithSize:CGSizeMake(100, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil].size;

这里主要的作用是在确定width,根据text长度换行后,计算height。

也可以确定height,来计算width。

//计算大小
CGSize userSize = [testStr boundingRectWithSize:CGSizeMake(CGFLOAT_MAX 200) options:NSStringDrawingTruncatesLastVisibleLine attributes:dic context:nil].size;

只需要将其中的width,height交换,让height确定(这里确定height为200),让width为CGFLOAT_MAX即可。

注:结果需取整

相关文章

网友评论

    本文标题:iOS开发-自定义UILabel

    本文链接:https://www.haomeiwen.com/subject/jntbhttx.html