iOS 设置label的行间距教程

2025-10-08 09:11:10

设置label的行间距,label默认多行显示,行与行间紧挨着不美观,通过调整行间距使其美观

方法/步骤

创建一个普通的label用来对比效果

    UILabel *label = [[UILabel alloc]init];

    label.frame=CGRectMake(10, 50, 70, 60);

    label.text=@"修改前\n行间距";

    label.numberOfLines=2;

    label.backgroundColor=[UIColor grayColor];

    label.textColor=[UIColor blackColor];

    [self.view addSubview:label];

    

iOS 设置label的行间距教程

    //方式一

    UILabel *label2 = [[UILabel alloc]init];

    label2.frame=CGRectMake(100, 50, 70, 60);

    label2.text=@"修改后\n行间距";

    label2.numberOfLines=2;

    label2.backgroundColor=[UIColor grayColor];

    label2.textColor=[UIColor blackColor];

    [label2 setValue:@(25) forKey:@"lineSpacing"];

    [self.view addSubview:label2];

iOS 设置label的行间距教程

     //方式二

    UILabel *label3 = [[UILabel alloc]init];

    label3.frame=CGRectMake(200, 50, 70, 60);

    label3.text=@"修改后\n行间距";

    label3.numberOfLines=2;

    label3.backgroundColor=[UIColor grayColor];

    label3.textColor=[UIColor blackColor];

    [self.view addSubview:label3];

    //通过修改文本属性

     NSMutableAttributedString *attriString =

     [[NSMutableAttributedString alloc] initWithString:label3.text];

     NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];

    [paragraphStyle setLineSpacing:10];//设置距离

    [attriString addAttribute:NSParagraphStyleAttributeName

                             value:paragraphStyle

                             range:NSMakeRange(0, [label3.text length])];

    label3.attributedText = attriString;

iOS 设置label的行间距教程

方式一和方式二均可以调整行间距,但通过修改文本属性调整行间距效果更好些

iOS 设置label的行间距教程

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢