iOS设置UILabel的行间距并自适应高度

时间:2021-08-12 06:09:38

    // label根据文字自适应高度

    self.tailLabel.numberOfLines = 0;

    self.tailLabel.lineBreakMode = NSLineBreakByWordWrapping;

    CGSize size = [self.tailLabel sizeThatFits:CGSizeMake(self.tailLabel.frame.size.width, MAXFLOAT)];

    CGRect frame = self.tailLabel.frame;

    frame.size.height = size.height;

    self.tailLabel.frame = frame;

    // 设置label的行间距

    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:tail];

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

    [paragraphStyle setLineSpacing:k6AutoSize(8)];

    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [tail length])];

    [self.tailLabel setAttributedText:attributedString];

    [self.tailLabel sizeToFit];