UILabel关于支持HTML格式 自动换行 行间距的封装

在APP开发中,会经常出现大段的文字,为了排版的好看需要进行排版,现在封装了两个方法,分别输入字符串,字体,字体颜色,行间距和控件的大小,即可返回一个UILabel,支持自动折行,第一个方法输入的是普通的字符串,第二个方法输入的是HTML字符串.代码如下:


/* 普通字符串 */

- (UILabel *)returnLineSpacingLabelWithText:(NSString *)text font:(UIFont *)font textColor:(UIColor *)textColor lineSpace:(float)lineSpace frame:(CGRect)frame

{

    UILabel *label = [[UILabel alloc] initWithFrame:frame];

    label.font = font;

    label.textColor = textColor;

    label.textAlignment = NSTextAlignmentCenter;

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

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

    [paragraphStyle setLineSpacing:lineSpace];

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

    label.attributedText = attributedString;

    label.numberOfLines = 0;

    [label sizeToFit];

    

    return label;

}


/* HTML字符串 */

- (UILabel *)returnLineSpacingLabelWithHtmlText:(NSString *)text font:(UIFont *)font textColor:(UIColor *)textColor lineSpace:(float)lineSpace frame:(CGRect)frame

{

    UILabel *label = [[UILabel alloc] initWithFrame:frame];

    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithData:[text dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];

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

    [paragraphStyle setLineSpacing:lineSpace];

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

    label.attributedText = attrStr;

    label.font = font;

    label.textColor = textColor;

    label.numberOfLines = 0;

    [label sizeToFit];

    

    return label;

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值