調節UILabel的行間距

征途LN發表於2015-01-12

UILabel 本身沒有提供調節行間距的介面,但是字串提供了修改其表示格式的方法,可簡單表示如下:

 introduce = @"來得及發垃圾發酵了放假啊理解費拉達斯肌膚垃圾的酸辣粉阿拉斯加法拉盛大家發垃圾啊的勝利解放啦放假啦大家費拉達斯家啦";
    CGSize maxSize = CGSizeMake(ScreenSize.width-40, 500000); //設定字串顯示的最大區域

    NSDictionary * contentAttribute = @{NSFontAttributeName:[UIFont systemFontOfSize:15]};
    NSMutableAttributedString * attributeStr = [[NSMutableAttributedString alloc]initWithString:introduce attributes:contentAttribute];

    NSMutableParagraphStyle * style = [[NSMutableParagraphStyle alloc]init];
    style.lineSpacing = 8; //設定行間距
    [attributeStr addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, introduce.length)];

    CGSize size = [attributeStr boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;//獲取字元內容所佔的區域

    _introduceLabel.attributedText = attributeStr;
    _introduceLabel.frame = CGRectMake(20, 13, ScreenSize.width-40, size.height);


相關文章