NSMutableAttributedString的使用

本文介绍了一个 iOS 应用开发中的 UILabel 控件使用案例,详细展示了如何通过 NSMutableParagraphStyle 设置 UILabel 中文本的行间距,并在文本变化时更新行间距。

 

#import "ViewController.h"

 

@interface ViewController ()

@property (nonatomic, strong) UILabel *lable;

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    self.lable = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, 300, 200)];

    self.lable.numberOfLines = 0;

    _lable.text = [NSString stringWithFormat:@"丁凯乐是《快乐星球1》[1-2]  主角。在《快乐星球2》中客串。丁凯乐(小名乐乐)是现实生活中阳光小学四年级的学生,像中国大多数10岁左右的孩子一样"];

    _lable.textAlignment = NSTextAlignmentLeft;

    _lable.font = [UIFont systemFontOfSize:14];

    [self.view addSubview:_lable];

    //设置行间距为9

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

    [paragraphStyle setLineSpacing:9];

    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:_lable.text];

    [attributedString addAttributes:@{NSParagraphStyleAttributeName:paragraphStyle} range:NSMakeRange(0, [_lable.text length])];

    _lable.attributedText = attributedString;

    

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

    button.frame = CGRectMake(20, 500, 100, 50);

    button.backgroundColor = [UIColor redColor];

    [button addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:button];

 

}

// lable上的文字发生改变,必须重新设置行间距,否则改变后的文字的行间距依然没有变

-(void)click

{

    self.lable.text = @"丁凯乐是《快乐星球1》[1-2]  主角。在《快乐星球2》中客串。丁凯乐(小名乐乐)是现实生活中阳光小学四年级的学生,像中国大多数10岁左右的孩子一样,他的生活平静、普通而且按部就班。但是由于他的性格内向、胆小怕事,在学校他经常被班里几个调皮的同学金刚、胖哥和小九九欺负,乐乐惹不起他们,只好忍气吞声。";

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

    [paragraphStyle setLineSpacing:9];

    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:_lable.text];

    [attributedString addAttributes:@{NSParagraphStyleAttributeName:paragraphStyle} range:NSMakeRange(0, [_lable.text length])];

    _lable.attributedText = attributedString;

 

   }

转载于:https://my.oschina.net/daxiaLKS/blog/717761

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值