本文介绍怎么使一段文字中部分文字变颜色,并带有点击事件
实现方法
- textView富文本实现文本变色
- textView代理方法实现点击事件
代码
UITextView *contentTV = [[UITextView alloc] init];
//不要忘记设置frame!
NSString *descText = @"第一个段落;\n\n首次购买***神器需去个人资料里设置收货者的收货地址,设置后平台将自动发货,没有设置收货地址的用户将不能正常收到货物;\n\n第3个段落;\n\n使用方法请去使用教程中查看。";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:descText];
[attributedString addAttribute:NSLinkAttributeName
value:@"ProvidentFundshuaxin://"
range:[[attributedString string] rangeOfString:@"使用教程"]];
[attributedString addAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:13]} range:[descText rangeOfString:@"使用教程"]];
contentTV.attributedText = attributedString;
contentTV.linkTextAttributes = @{NSForegroundColorAttributeName: C_465F7D,
NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)};
contentTV.textColor = C_9B9B9B;
contentTV.delegate = self;
contentTV.editable = NO; //必须禁止输入,否则点击将弹出输入键盘
contentTV.scrollEnabled = NO;
[self.view addSubview:contentTV];
#pragma mark ---- textView Delegate ----
-(BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange{
NSRange range = [@"第一个段落;\n\n首次购买***神器需去个人资料里设置收货者的收货地址,设置后平台将自动发货,没有设置收货地址的用户将不能正常收到货物;\n\n第3个段落;\n\n使用方法请去使用教程中查看。" rangeOfString:@"使用教程"];
if (NSEqualRanges(characterRange, range)) {
SXWebViewController *vc = [[SXWebViewController alloc] init];
vc.navigationItemTitle = @"使用教程";
vc.urlLinkStr = @"https://www.baidu.com";
[self.navigationController pushViewController:vc animated:YES];
}
return YES;
}
如果本文有帮到你,希望给个小心心支持一下~
网友评论