新建分类如下:
编辑UILabel+LabelHH.h如下:
//
// UILabel+LabelHH.h
// 日志信息之UITabBar与UINavigationBar的结合使用
//
// Created by apple on 15/9/8.
// Copyright (c) 2015年 LiuXun. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UILabel (LabelHH)
-(void)setDefaultStyleBy:(NSString *) text;
- (float) heightForStringByWidth:(float )width;
@end
编辑UILabel+LabelHH.m如下:
//
// UILabel+LabelHH.m
// 日志信息之UITabBar与UINavigationBar的结合使用
//
// Created by apple on 15/9/8.
// Copyright (c) 2015年 LiuXun. All rights reserved.
//
#import "UILabel+LabelHH.h"
@implementation UILabel (LabelHH)
-(void)setDefaultStyleBy:(NSString *) text
{
NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:text];
//段落样式
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
// 设置段落行间距
paragraphStyle.lineSpacing = 5;
// 设置段落间距
paragraphStyle.paragraphSpacing = 10;
// 设置书写方向
paragraphStyle.baseWritingDirection = NSWritingDirectionLeftToRight;
// 设置对齐方式
paragraphStyle.alignment = NSTextAlignmentLeft;
// 设置首行缩进
paragraphStyle.firstLineHeadIndent = 20;
// 设置首行以外的其它行缩进
paragraphStyle.headIndent = 10;
// 设置每行容纳字符的宽度
paragraphStyle.tailIndent = self.frame.size.width;
// 为富文本添加以上的段落属性
[attr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, text.length)];
// 设置富文本的字体
[attr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13] range:NSMakeRange(0, text.length)];
// 设置富文本的字体颜色
[attr addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0x6c6c6c) range:NSMakeRange(0, text.length)];
self.numberOfLines = 0;
self.attributedText = attr;
CGFloat x = self.frame.origin.x;
CGFloat y = self.frame.origin.y;
CGFloat wid = self.frame.size.width;
CGFloat hig = [self heightForStringByWidth:wid];
self.frame = CGRectMake(x, y, wid, hig);
self.backgroundColor = [UIColor whiteColor];
self.attributedText = attr;
}
- (float) heightForStringByWidth:(float )width{
CGSize sizeToFit = [self sizeThatFits:CGSizeMake(width, MAXFLOAT)];
return sizeToFit.height;
}
@end
在使用时只需要新建pch文件 把此分类的头文件导入即可在工程任何地方使用:
使用时只需要新建UIlabel 然后调用
<pre name="code" class="objc">(void)setDefaultStyleBy:(NSString *) text
// text是要显示的文章内容
即可:调用代码不再详述
运行结果如下: