项目中要实现的效果
1.现在较好的第三方 TYAttributedLabel可以很方便的实现各种富文本效果
但是项目中用到富文本效果的地方不是很多,所以自己就想找个更加简单的方法.具体方法如下
先设置NSLinkAttributeName属性
//用UItextView 实现富文本的功能
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:@"*登录即表示你同意《体教联盟用户协议》"];
NSMutableParagraphStyle *paragraphStyleFirst = [[NSMutableParagraphStyle alloc] init];
paragraphStyleFirst.alignment = NSTextAlignmentCenter;
//绑定标签跳转
[myStr addAttribute:NSLinkAttributeName
value:@"mytest://"
range:[[myStr string] rangeOfString:@"《体教联盟用户协议》"]];
[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代理方法,点击link时拦截
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
if ([[URL scheme] isEqualToString:@"mytest"]) {
//跳转界面或者其他事情
return NO;
}
return YES;
}