1. 程式人生 > >UILabel關於支援HTML格式 自動換行 行間距的封裝

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 = [[NSMutableAttributedStringalloc] initWithString:text];

NSMutableParagraphStyle *paragraphStyle = [[

NSMutableParagraphStylealloc] 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 = [[NSMutableAttributedStringalloc] initWithData:[text dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType}documentAttributes:nilerror:nil];

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStylealloc] 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;

}