iOS UILabel富文本

iOS UILabel富文本_第1张图片

NSString *str = @"黄河远上白云间,一片孤城万仞山。\n等羌笛何须怨杨柳,春风不度玉门关\n日照香炉生紫烟,遥看瀑布挂前川。\n飞流直下三千尺,疑是银河落九天。";
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:str];
    //attrStr添加字体和设置字体的范围
    
    [attrStr addAttribute:NSFontAttributeName
                    value:[UIFont systemFontOfSize:30.0f]
                    range:NSMakeRange(0, 3)];
    //attrStr添加文字颜色
    
    [attrStr addAttribute:NSForegroundColorAttributeName
                    value:[UIColor redColor]
                    range:NSMakeRange(17, 7)];
   // attrStr添加下划线
    
    [attrStr addAttribute:NSUnderlineStyleAttributeName
                    value:[NSNumber numberWithInteger:NSUnderlineStyleSingle]
                    range:NSMakeRange(8, 7)];
    //段落样式
    
    NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
    //行间距
    paragraph.lineSpacing = 10;
    //段落间距
    paragraph.paragraphSpacing = 20;
    //对齐方式
    paragraph.alignment = NSTextAlignmentLeft;
    //指定段落开始的缩进像素
    paragraph.firstLineHeadIndent = 30;
    //调整全部文字的缩进像素
    paragraph.headIndent = 10;
    //attrStr添加段落设置
    
    [attrStr addAttribute:NSParagraphStyleAttributeName
                    value:paragraph
                    range:NSMakeRange(0, [str length])];
    
    //创建label
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 300, 0)];
    label.backgroundColor = [UIColor lightGrayColor];
    //自动换行
    label.numberOfLines = 0;
    //设置label的富文本
    label.attributedText = attrStr;
    //label高度自适应
    [label sizeToFit];
    [self.view addSubview:label];
   // 设置sizeToFit之后是可以取出label的高度的,这样做label高度自适应。
    
    CGFloat height = label.frame.size.height;
    NSLog(@"H = %f",height);



你可能感兴趣的:(ios)