2024年3月26日发(作者:)

本文由我司收集整编,推荐下载,如有疑问,请与我司联系

【iOS开发】如何给字符串添加超连接(响应事件)

, 16-06-29 17:06:25 * @brief 创建textView-(void)createTextView //字符串的处理

NSString *str =@”@百度是大坏蛋@baidu”; NSString *matchStr = @”百度”;

NSMutableAttributedString *MAttributedString = [[NSMutableAttributedString

alloc]initWithString:str]; if ([str rangeOfString:matchStr].location!=NSNotFound) { * 注

意这个url必须是*****://***的格式不然url取不到字符串 [MAttributedString

addAttribute:NSLinkAttributeName value:[NSURL URLWithString:@”username://”]

range:[[MAttributedString string] rangeOfString:matchStr]]; //UITextView的创建

UITextView *TV = [[UITextView alloc]initWithFrame:CGRectMake(0, 60, 300, 200)];

oundColor = [UIColor grayColor]; //必须设为NO不然不能响应点击事件

le = NO; // 设置点击时的样式 NSDictionary *linkAttributes

[UIColor

[UIColor

=@{NSForegroundColorAttributeName:

greenColor],NSUnderlineColorAttributeName:

lightGrayColor],NSUnderlineStyleAttributeName:@(NSUnderlinePatternSolid)}; // 添加

链接文字 xtAttributes = linkAttributes; /** 设置自动检测类型为链接网址.

*/ tectorTypes = UIDataDetectorTypeLink; te = self;

utedText = MAttributedString; [ addSubview:TV];#pragma mark -

textViewDelegate- (BOOL)textView:(UITextView

*)URL

*)textView

shouldInteractWithURL:(NSURL inRange:(NSRange)characterRange

NSLog(@”%@”,[URL scheme]); if ([[URL scheme] containsString:@”username”]) {

NSLog(@”点中了。。。。。。。。”); return YES;//跳转到浏览器不过你们可以把它封装成

一个类来使用,不过也有几个需要注意的点

  添加属性链接的URL需要注意的地方,必须使用xxxx://xxxx的格式。

  /** * 注意这个url必须是 span *****://*** /span 的格式不然url取不到字符串

[MAttributedString addAttribute:NSLinkAttributeName value:[NSURL