设置UILabel的行间距

2018-03-31  本文已影响18人  青山不改

有时候设计师出的图,字体行间距会有特殊要求,因为默认间距太挤了,此时就需要代码设置一下:
OC:

- (NSAttributedString *)setLineSpaceWith:(CGFloat)space
                                    font:(UIFont *)font
                                    text:(NSString *)text{
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    paragraphStyle.lineSpacing = space - (font.lineHeight - font.pointSize);
    NSDictionary *dic = @{NSParagraphStyleAttributeName: paragraphStyle};
    NSAttributedString *attr = [[NSAttributedString alloc]initWithString:text attributes:dic];
    return attr;
}

Swift:

func setTextLineSpace(text: String,
                     space: CGFloat,
                      font: UIFont) -> NSAttributedString {
        
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = space - (font.lineHeight - font.pointSize)
        let text = NSAttributedString.init(string: text, attributes: [NSAttributedStringKey.paragraphStyle: paragraphStyle])
        
        return text
    }
上一篇下一篇

猜你喜欢

热点阅读