YYText参考文档
TTTAttributedLabel参考文档
富文本的处理原生文案略显麻烦文章链接。
相比而言,YYText使用简单且功能强大,YYLabel 设置字体样式更方便简洁。另外TTTAttributedLabel也挺不错的。
YYText
基础用法
//基本用法和UILabel相似
YYLabel *label = [[YYLabel alloc]init];
label.frame = CGRectMake(0, 0, 200, 200);
label.center = self.view.center;
label.numberOfLines = 2;
label.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:label];
属性文本
NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:@"Change the fucking world"];
//字体
str.yy_font = [UIFont systemFontOfSize:20];
//颜色
str.yy_color = [UIColor orangeColor];
[str yy_setColor:[UIColor greenColor] range:NSMakeRange(7, 4)];
//也可以直接搜索相应文字改变属性
//NSRange range = [[text string] rangeOfString:@"对这个世界如果你有太多的抱怨"
// options:NSCaseInsensitiveSearch];
//行间距
str.yy_lineSpacing =10;
//首行缩进
str.yy_firstLineHeadIndent = 10;
//文字描边(空心字)默认黑色
//必须设置width
[text yy_setStrokeColor:[UIColor orangeColor] ];
[text yy_setStrokeWidth:@(2) ];
//文字装饰
YYTextDecoration * decoration
= [YYTextDecoration decorationWithStyle:YYTextLineStyleSingle
width:@(1)
color:[UIColor blueColor]];
//删除样式
[text yy_setTextStrikethrough:decoration
range:range];
//下划线
[text yy_setTextUnderline:decoration
range:range];
//阴影
NSShadow *shadow = [[NSShadow alloc]init];
shadow.shadowColor = [UIColor grayColor];
shadow.shadowOffset = CGSizeMake(1, 1.5);
shadow.radius = 5;
str.yy_shadow = shadow;
//文本内阴影
YYTextShadow *shadow = [YYTextShadow new];
shadow.color = [UIColor redColor];
shadow.offset = CGSizeMake(0, 2);
shadow.radius = 1;
[str yy_setTextInnerShadow:shadow ];
//背景框
//多行显示时效果会不太如愿
str.yy_textBorder = [ YYTextBorder borderWithLineStyle:YYTextLineStylePatternCircleDot
lineWidth:1
strokeColor:[UIColor greenColor]];
str.yy_textBorder.cornerRadius = 3;
str.yy_textBorder.insets = UIEdgeInsetsMake(0, -2, 0, -2);
#pragma mark - 可点击高亮显示
[str yy_setTextHighlightRange:range
color:[UIColorr redColor]
backgroundColor:[UIColor greenColor]
tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){
//点击事件
}];
//一定要放在最后
label.attributedText = str;
}
YYAttachment
NSMutableAttributedString *text = [NSMutableAttributedString new];
UIFont *font = [UIFont systemFontOfSize:16];
{
NSString *title = @"This is UIImage attachment:";
[text appendAttributedString:[[NSAttributedString alloc] initWithString:title attributes:nil]];
//压缩
UIImage *image = [UIImage imageNamed:@"dribbble64_imageio"];
image = [UIImage imageWithCGImage:image.CGImage
scale:2
orientation:UIImageOrientationUp];
NSMutableAttributedString *attachText
= [NSMutableAttributedString yy_attachmentStringWithContent:image
contentMode:UIViewContentModeCenter
attachmentSize:image.size
alignToFont:font
alignment:YYTextVerticalAlignmentCenter];
[text appendAttributedString:attachText];
[text appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n" attributes:nil]];
}
{
NSString *title = @"This is UIView attachment: ";
[text appendAttributedString:[[NSAttributedString alloc] initWithString:title attributes:nil]];
UISwitch *switcher = [UISwitch new];
[switcher sizeToFit];
NSMutableAttributedString *attachText
= [NSMutableAttributedString yy_attachmentStringWithContent:switcher
contentMode:UIViewContentModeCenter
attachmentSize:switcher.size
alignToFont:font
alignment:YYTextVerticalAlignmentCenter];
[text appendAttributedString:attachText];
[text appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n" attributes:nil]];
}
{
YYImage *image = [YYImage imageNamed:@"pia"];
image.preloadAllAnimatedImageFrames = YES;
YYAnimatedImageView *imageView = [[YYAnimatedImageView alloc] initWithImage:image];
imageView.autoPlayAnimatedImage = NO;
[imageView startAnimating];
NSMutableAttributedString *attachText
= [NSMutableAttributedString yy_attachmentStringWithContent:imageView
contentMode:UIViewContentModeCenter
attachmentSize:imageView.size
alignToFont:font
alignment:YYTextVerticalAlignmentBottom];
[text appendAttributedString:attachText];
[text appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n" attributes:nil]];
}
YYTextLayout
NSAttributedString *text = ...
CGSize size = CGSizeMake(100, CGFLOAT_MAX);
YYTextLayout *layout = [YYTextLayout layoutWithContainerSize:size
text:text];
// get text bounding
layout.textBoundingRect; // get bounding rect
layout.textBoundingSize; // get bounding size
// query text layout
[layout lineIndexForPoint:CGPointMake(10,10)];
[layout closestLineIndexForPoint:CGPointMake(10,10)];
[layout closestPositionToPoint:CGPointMake(10,10)];
[layout textRangeAtPoint:CGPointMake(10,10)];
[layout rectForRange:[YYTextRange rangeWithRange:NSMakeRange(10,2)]];
[layout selectionRectsForRange:[YYTextRange rangeWithRange:NSMakeRange(10,2)]];
// text layout display
YYLabel *label = [YYLabel new];
label.size = layout.textBoundingSize;
label.textLayout = layout;
YYTextRubyAnnotation
NSMutableAttributedString *one = [[NSMutableAttributedString alloc] initWithString:@"这是用汉语写的一段文字。"];
one.yy_font = [UIFont boldSystemFontOfSize:30];
YYTextRubyAnnotation *ruby;
ruby = [YYTextRubyAnnotation new];
ruby.textBefore = @"hàn yŭ";
[one yy_setTextRubyAnnotation:ruby
range:[one.string rangeOfString:@"汉语"]];
ruby = [YYTextRubyAnnotation new];
ruby.textBefore = @"wén";
[one yy_setTextRubyAnnotation:ruby range:[one.string rangeOfString:@"文"]];
ruby = [YYTextRubyAnnotation new];
ruby.textBefore = @"zì";
ruby.alignment = kCTRubyAlignmentCenter;
[one yy_setTextRubyAnnotation:ruby range:[one.string rangeOfString:@"字"]];
YYLabel *label = [YYLabel new];
label.backgroundColor = [UIColor whiteColor];
label.attributedText = one;
label.frame = CGRectMake(0, 10, self.view.frame.size.width, 200);
label.textAlignment = NSTextAlignmentCenter;
label.textVerticalAlignment = YYTextVerticalAlignmentCenter;
label.numberOfLines = 1;
[self.view addSubview:label];
TTTAttributed
//也可以是NSString字符串
NSMutableAttributedString *attString
= [[NSMutableAttributedString alloc] initWithString:@"对这个世界如果你有太多的抱怨 \n跌倒了 就不敢继续往前走 \n为什麼 人要这麼的脆弱 堕落\n请你打开电视看看\n为生命在努力勇敢的走下去\n还记得你说家是唯一的城堡\n随著稻香河流继续奔跑\n微微笑 小时候的梦我知道"];
__block CGSize size;
[self.label setText:attString afterInheritingLabelAttributesAndConfiguringWithBlock:^NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
NSRange fontRange
= [[mutableAttributedString string] rangeOfString:@"对这个世界如果你有太多的抱怨"
options:NSCaseInsensitiveSearch];
NSRange strokeColorRange1
= [[mutableAttributedString string] rangeOfString:@"跌倒了 就不敢继续往前走"
options:NSCaseInsensitiveSearch];
NSRange strikeRange
= [[mutableAttributedString string] rangeOfString:@"为什麼 人要这麼的脆弱 堕落"
options:NSCaseInsensitiveSearch];
NSRange fillColorRange
= [[mutableAttributedString string] rangeOfString:@"请你打开电视看看"
options:NSCaseInsensitiveSearch];
NSRange shadowRange
= [[mutableAttributedString string] rangeOfString:@"为生命在努力勇敢的走下去"
options:NSCaseInsensitiveSearch];
NSRange obliquenessRange
= [[mutableAttributedString string] rangeOfString:@"还记得你说家是唯一的城堡"
options:NSCaseInsensitiveSearch];
UIEdgeInsets fillPadding = UIEdgeInsetsMake(0, 0, 0, 0);
// Core Text APIs use C functions without a direct bridge to UIFont.
// See Apple's "Core Text Programming Guide" to learn how to configure string attributes.
UIFont *boldSystemFont = [UIFont boldSystemFontOfSize:16];
CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)boldSystemFont.fontName, boldSystemFont.pointSize, NULL);
if (font) {
{
//字体
[mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName
value:(__bridge id)font
range:fontRange];
//文字颜色
[mutableAttributedString addAttribute:(NSString *)kCTForegroundColorAttributeName
value:[UIColor redColor]
range:fontRange];
CFRelease(font);
}
{
//NSStrokeColorAttributeName设置文字描边颜色,
//需要和NSStrokeWidthAttributeName设置描边宽度,这样就能使文字空心
//文字描边颜色
[mutableAttributedString addAttribute:NSStrokeColorAttributeName
value:[UIColor blueColor]
range:strokeColorRange1];
//文字描边宽度
[mutableAttributedString addAttribute:NSStrokeWidthAttributeName
value:@(2.0)
range:strokeColorRange1];
}
{
//删除样式
[mutableAttributedString addAttribute:kTTTStrikeOutAttributeName
value:@YES
range:strikeRange];
//加上下划线
[mutableAttributedString addAttribute:NSUnderlineStyleAttributeName
value:[NSNumber numberWithInt:3]
range:strikeRange];
[mutableAttributedString addAttribute:NSUnderlineColorAttributeName
value:[UIColor greenColor]
range:strikeRange];
}
{
//背景色
[mutableAttributedString addAttribute:kTTTBackgroundFillColorAttributeName
value:[UIColor purpleColor]
range:fillColorRange];
//控制背景色范围
[mutableAttributedString addAttribute:kTTTBackgroundFillPaddingAttributeName
value:[NSNumber valueWithUIEdgeInsets:fillPadding]
range:fillColorRange];
//控制背景色(文字边框)的圆角
[mutableAttributedString addAttribute:kTTTBackgroundCornerRadiusAttributeName
value:@(4)
range:fillColorRange];
//文字边框颜色
[mutableAttributedString addAttribute:kTTTBackgroundStrokeColorAttributeName
value:[UIColor purpleColor]
range:fillColorRange];
}
{
//无效
NSShadow *shadow = [[NSShadow alloc] init];
[shadow setShadowColor:[UIColor redColor]];
[shadow setShadowBlurRadius:4.0];
[shadow setShadowOffset:CGSizeMake(2, 2)];
//阴影
[mutableAttributedString addAttribute:NSShadowAttributeName
value:shadow
range:shadowRange];
}
{
//无效
//斜体
//NSObliquenessAttributeName 设置字体倾斜度,取值为 NSNumber(float),正值右倾,负值左倾
[mutableAttributedString addAttribute:NSObliquenessAttributeName
value:@(5.0)
range:obliquenessRange];
}
}
//高度计算
size = [TTTAttributedLabel sizeThatFitsAttributedString:mutableAttributedString
withConstraints:CGSizeMake(kScreenWidth, CGFLOAT_MAX)
limitedToNumberOfLines:0];
return mutableAttributedString;
}];
NSRange boldRange1 = [attString.string rangeOfString:@"随著稻香河流继续奔跑" options:NSCaseInsensitiveSearch];
[self.label addLinkToURL:[NSURL URLWithString:@"http://y.qq.com/portal/song/003aAYrm3GE0Ac.html"]
withRange:boldRange1];
NSRange addressRange = [attString.string rangeOfString:@"微微笑 小时候的梦我知道" options:NSCaseInsensitiveSearch];
[self.label addLinkToAddress:@{@"detailAdd":@"幸福街122号",
@"lontitude":@"110.011111",
@"latitude":@"30.1234"}
withRange:addressRange];
//电话号码可以自动识别,也可以这样添加
//NSRange phoneRange = [text rangeOfString:phoneNum options:NSCaseInsensitiveSearch];
//[self.label addLinkToPhoneNumber:phoneNum withRange:phoneRange];
self.label.frame = CGRectMake(0, 100, kScreenWidth, size.height);
[self.view addSubview:self.label];
TTTAttributedLabel 的懒加载
if (!_label) {
_label = [[TTTAttributedLabel alloc]initWithFrame:CGRectZero];
_label.lineBreakMode = NSLineBreakByTruncatingHead;
_label.numberOfLines = 0;
_label.delegate = self;
_label.lineSpacing = 10;
/*
要放在`text`,
`setText:`
`setText:afterInheritingLabelAttributesAndConfiguringWithBlock:前面才有效
*/
_label.enabledTextCheckingTypes = NSTextCheckingTypePhoneNumber|
NSTextCheckingTypeAddress|
NSTextCheckingTypeLink;
//链接正常状态文本属性
_label.linkAttributes = @{
NSForegroundColorAttributeName:[UIColor purpleColor],
NSUnderlineStyleAttributeName:@(1)
};
//链接高亮状态文本属性
_label.activeLinkAttributes = @{
NSForegroundColorAttributeName:[UIColor redColor],
NSUnderlineStyleAttributeName:@(1)
};
}
return _label;
TTTAttributedLabel 是代理方法实现所有点击回调
#pragma mark - TTTAttributedLabelDelegate
//点击链接
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url{
NSLog(@"linkClick");
[[UIApplication sharedApplication] openURL:url];
}
//点击地址链接
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithAddress:(NSDictionary *)addressComponents{
NSLog(@"addressClick");
NSLog(@"detailAdd:%@,lontitude:%f,latitude:%f",
addressComponents[@"detailAdd"],
[addressComponents[@"lontitude"] floatValue],
[addressComponents[@"latitude"] floatValue]);
}
//拨的电话
- (void)attributedLabel:(TTTAttributedLabel *)label
didSelectLinkWithPhoneNumber:(NSString *)phoneNumber{
NSLog(@"phoneClick");
}