在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;
}