闲来无事,简单整理了下富文本的一些使用方法;话不多说,直接上代码:
控件布局用的是 Masonry,字体用的是 迷你简汉真广标(使用外部字体见上篇文章),
#pragma mark - 创建可变字符串的lb
- (void)buildAttributedString
{
UIScrollView *mainScroView = [[UIScrollView alloc]init];
mainScroView.showsVerticalScrollIndicator = NO;
mainScroView.showsHorizontalScrollIndicator = NO;
[self.view addSubview:mainScroView];
[mainScroView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.right.bottom.left.mas_equalTo(0);
}];
NSString *str = @"而在梅新育看来,单一的财税政策,也很难提振美国经济,还需要跟接下来的福利等一系列社会改革结合起来,才能发挥最好的作用。这一点,自然也是跨国资本需要审慎考虑的。梅新育指出,很重要的一点是,“从特朗普访华称中国的政体适合中国人民,到近期一系列的动作来看,他偏向于减少对外部世界的干预";
NSMutableAttributedString * attributeStr = [[NSMutableAttributedString alloc]initWithString:str];
/** 字体大小 */
[attributeStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:[self getMnjhzgbFont] size:15 *HEIGHT] range:NSMakeRange(0, 10)];
[attributeStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20 *HEIGHT] range:NSMakeRange(10, str.length - 10)];
/** 字体颜色 */
[attributeStr addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, 10)];
[attributeStr addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(10, str.length - 10)];
/** 背景色 */
[attributeStr addAttribute:NSBackgroundColorAttributeName value:[UIColor lightGrayColor] range:NSMakeRange(0, 10)];
[attributeStr addAttribute:NSBackgroundColorAttributeName value:[UIColor yellowColor] range:NSMakeRange(10, str.length - 10)];
/** 删除线 */
[attributeStr addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(0, 10)];
/** 下划线 */
[attributeStr addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(10, str.length - 10)];
/** 字体的阴影 */
NSShadow *shadow = [[NSShadow alloc]init];
/** 阴影的清晰度 */
shadow.shadowBlurRadius = 1;//模糊度
shadow.shadowColor = [UIColor lightGrayColor];
/**
CGSizeMake(x,y)
x为正,为往右偏移
y为正,为往上偏移
*/
shadow.shadowOffset = CGSizeMake(0, -3);
/** 阴影 */
[attributeStr addAttribute:NSShadowAttributeName value:shadow range:NSMakeRange(10, str.length - 10)];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
/** 行间距 */
paragraphStyle.lineSpacing = 20 *HEIGHT;
[attributeStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, str.length)];
UILabel *attributeLb = [[UILabel alloc]init];
attributeLb.attributedText = attributeStr;
attributeLb.numberOfLines = 0;
attributeLb.layer.borderColor = [UIColor blackColor].CGColor;
attributeLb.layer.borderWidth = 1.0;
[mainScroView addSubview:attributeLb];
[attributeLb mas_makeConstraints:^(MASConstraintMaker *make) {
make.centerX.mas_equalTo(0);
make.top.mas_equalTo(60*HEIGHT);
make.width.mas_equalTo(300*WIDTH);
}];
[attributeLb layoutIfNeeded];
NSLog(@"%f",attributeLb.frame.size.height);
mainScroView.contentSize = CGSizeMake(SCREEN_WIDTH, attributeLb.frame.size.height + 120 *HEIGHT);
}
效果展示: