項(xiàng)目中要實(shí)現(xiàn)的效果
需求.png
1.現(xiàn)在較好的第三方 TYAttributedLabel可以很方便的實(shí)現(xiàn)各種富文本效果
但是項(xiàng)目中用到富文本效果的地方不是很多,所以自己就想找個(gè)更加簡(jiǎn)單的方法.具體方法如下
先設(shè)置NSLinkAttributeName屬性
//用UItextView 實(shí)現(xiàn)富文本的功能
UITextView *detail = [[UITextView alloc] initWithFrame:CGRectMake(0, ViewMaxY(loginBtn)+10, SCREEN_WIDTH, 30)];
detail.backgroundColor = RGB(249, 249, 249);
detail.font = [UIFont systemFontOfSize:14];
detail.textAlignment = NSTextAlignmentCenter;
detail.delegate = self;
detail.editable = NO;
detail.scrollEnabled = NO;
NSMutableAttributedString *myStr = [[NSMutableAttributedString alloc] initWithString:@"*登錄即表示你同意《體教聯(lián)盟用戶協(xié)議》"];
NSMutableParagraphStyle *paragraphStyleFirst = [[NSMutableParagraphStyle alloc] init];
paragraphStyleFirst.alignment = NSTextAlignmentCenter;
//綁定標(biāo)簽跳轉(zhuǎn)
[myStr addAttribute:NSLinkAttributeName
value:@"mytest://"
range:[[myStr string] rangeOfString:@"《體教聯(lián)盟用戶協(xié)議》"]];
[myStr addAttribute:NSForegroundColorAttributeName
value:RGB(153, 153, 153)
range:[[myStr string] rangeOfString:@"*登錄即表示你同意"]];
[myStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyleFirst range:NSMakeRange(0, myStr.length)];
detail.linkTextAttributes = @{NSForegroundColorAttributeName: RGB(80, 140, 238),
NSUnderlineColorAttributeName: [UIColor redColor],
NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)};
detail.attributedText = myStr;
然后在textView代理方法,點(diǎn)擊link時(shí)攔截
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
if ([[URL scheme] isEqualToString:@"mytest"]) {
//跳轉(zhuǎn)界面或者其他事情
return NO;
}
return YES;
}
最終實(shí)現(xiàn)效果
最終效果.gif