YYText使用
在开发中要使用到很多的富文本或者属性字符串,原来使用的是TTTAttributedLabel,现在的项目中使用YYText
1.带图片的富文本,有点击事件
NSMutableAttributedString *text = [NSMutableAttributedString new];
UIFont *font = [UIFont systemFontOfSize:12];
NSMutableAttributedString *testText = [NSMutableAttributedString new];
NSMutableAttributedString *attachment = nil;
UIImage *image = [UIImage imageNamed:@"check"];
attachment = [NSMutableAttributedString yy_attachmentStringWithContent:image
contentMode:UIViewContentModeCenter
attachmentSize:CGSizeMake(15, 15)
alignToFont:font
alignment:YYTextVerticalAlignmentCenter];
[testText appendAttributedString: attachment];
NSString *string = @" 已了解并同意《遵守实验室须知》";
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:string];
attrString.yy_font = font;
attrString.yy_color = [UIColor colorWithHexString:@"#666666"];
NSRange range = [string rangeOfString:@"《遵守实验室须知》"];
[attrString yy_setColor:[UIColor colorWithHexString:@"#19ADA9"] range:range];
[attrString yy_setTextHighlightRange:range
color:[UIColor colorWithHexString:@"#19ADA9"]
backgroundColor:[UIColor blueColor]
tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
[_self showMessage:[NSString stringWithFormat:@"Tap: %@",[text.string substringWithRange:range]]];
}];
[testText appendAttributedString: attrString];
[text appendAttributedString:testText];
[text appendAttributedString:[self padding]];
使用YYLabel
来显示
YYLabel *label = [YYLabel new];
label.attributedText = text;
label.width = self.view.width;
label.height = self.view.height - (kiOS7Later ? 64 : 44);
label.top = (kiOS7Later ? 64 : 0);
label.textAlignment = NSTextAlignmentCenter;
label.textVerticalAlignment = YYTextVerticalAlignmentCenter;
label.numberOfLines = 0;
label.backgroundColor = [UIColor colorWithWhite:0.933 alpha:1.000];//[UIColor orangeColor];
[self.view addSubview:label];
显示效果如下:
2.计算大小
使用YYTextLayout
//大小
CGSize size = CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX);
YYTextLayout *layout = [YYTextLayout layoutWithContainerSize:size text:text];
NSLog(@"textBoundingSize = %@", NSStringFromCGSize(layout.textBoundingSize));
NSLog(@"textBoundingRect = %@", NSStringFromCGRect(layout.textBoundingRect));
控制台输出结果为:
textBoundingSize = {204, 20}
textBoundingRect = {{0, 0.234375}, {203.45578124999997, 19.73046875}}
可见textBoundingSize
向上取整了