NSMutableAttributedString的使用

 

#import "ViewController.h"ide

 

@interface ViewController ()atom

@property (nonatomic, strong) UILabel *lable;spa

@end.net

 

@implementation ViewControllerorm

 

- (void)viewDidLoad {ci

    [super viewDidLoad];get

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

    

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

    self.lable.numberOfLines = 0;io

    _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;

 

   }

相关文章
相关标签/搜索