iOS 設置UILabel的行間距並自適應高度


NSString *contentStr = @"總以為,在最初的地方,有一個最原來的我,就也會有一個最原來的你";
    
    UILabel *tempLabel = [[UILabel alloc] init];
    //設置背景顏色
    tempLabel.backgroundColor = [UIColor redColor];
    //設置內容
    tempLabel.text = contentStr;
    //設置字體顏色
    tempLabel.textColor = [UIColor whiteColor];
    //設置字體大小
    tempLabel.font = [UIFont systemFontOfSize:15.0];
    //設置文本是否多行顯示
    tempLabel.numberOfLines = 0;
    tempLabel.lineBreakMode = NSLineBreakByWordWrapping;
    //設置UILabel根據文字自適應高度
    CGSize size = [tempLabel sizeThatFits:CGSizeMake(100, MAXFLOAT)];
    //設置frame
    tempLabel.frame = CGRectMake(50, 100, 100, size.height);
    [self.view addSubview:tempLabel];
    //設置label的行間距
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:contentStr];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:8];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [contentStr length])];
    [tempLabel setAttributedText:attributedString];
    [tempLabel sizeToFit];

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM