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跌倒了 就不敢繼續(xù)往前走 \n為什麼 人要這麼的脆弱 墮落\n請你打開電視看看\n為生命在努力勇敢的走下去\n還記得你說家是唯一的城堡\n隨著稻香河流繼續(xù)奔跑\n微微笑 小時候的夢我知道"];
__block CGSize size;
[self.label setText:attString afterInheritingLabelAttributesAndConfiguringWithBlock:^NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
NSRange fontRange
= [[mutableAttributedString string] rangeOfString:@"對這個世界如果你有太多的抱怨"
options:NSCaseInsensitiveSearch];
NSRange strokeColorRange1
= [[mutableAttributedString string] rangeOfString:@"跌倒了 就不敢繼續(xù)往前走"
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:@"隨著稻香河流繼續(xù)奔跑" 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;
//鏈接正常狀態(tài)文本屬性
_label.linkAttributes = @{
NSForegroundColorAttributeName:[UIColor purpleColor],
NSUnderlineStyleAttributeName:@(1)
};
//鏈接高亮狀態(tài)文本屬性
_label.activeLinkAttributes = @{
NSForegroundColorAttributeName:[UIColor redColor],
NSUnderlineStyleAttributeName:@(1)
};
}
return _label;
TTTAttributedLabel 是代理方法實現(xiàn)所有點擊回調
#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");
}