UILabel 自动换行 和支持换行符

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:@"你要放在label里的文本字符串  \n  换行符"];
    [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14]  range:NSMakeRange(0, str.length)];
    CGSize maxSize = CGSizeMake(kWidth - 40,MAXFLOAT);
    self.attrStrSize = [str boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
    self.firstLabel.attributedText = str;
}

-(UILabel *)firstLabel{
    
    if(!_firstLabel){
        
        _firstLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 20, self.attrStrSize.width, self.attrStrSize.height)];
        _firstLabel.numberOfLines = 0;//表示label可以多行显示
        _firstLabel.lineBreakMode = NSLineBreakByCharWrapping;//换行模式,与上面的计算保持一致。
        [self.view  addSubview:_firstLabel];
    }
    return _firstLabel;
}

你可能感兴趣的:(UILabel 自动换行 和支持换行符)