NSString * str = [NSString stringWithFormat:@"This is an example by @网页链接"];
NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:str];
NSRange urlRange = [str rangeOfString:@"@网页链接"];
[string addAttribute:NSLinkAttributeName
value:@"http://m.baidu.com"
range:urlRange];
[string addAttribute:NSForegroundColorAttributeName
value:[UIColor blueColor]
range:urlRange];
[string endEditing];
UITextView * textView = [[UITextView alloc] initWithFrame:CGRectMake(100, 50, 200, 200)];
textView.backgroundColor =[UIColor whiteColor];
textView.delegate = self;
[textView setSelectable: YES];
[textView setEditable:NO];
textView.attributedText = string;
textView.dataDetectorTypes = UIDataDetectorTypeLink;
[self.view addSubview:textView];
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
NSLog(@"%@",URL);
UIWebView *web = [[UIWebView alloc] initWithFrame:CGRectMake(0, 100, 375, 500)];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
[web loadRequest:request];
[self.view addSubview:web];
// return YES; //系统会用浏览器打开链接
return NO;
}
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] initWithData:nil ofType:nil] ;
textAttachment.image = [UIImage imageNamed:@"icon2"]; //要添加的图片
NSAttributedString *textAttachmentString = [NSAttributedString attributedStringWithAttachment:textAttachment] ;
[mut insertAttributedString:textAttachmentString atIndex:string.length-4];//index为用户指定要插入图片的位置,mut 是原来的a<span style="font-family: 'Helvetica Neue', Helvetica, STheiti, 微软雅黑, 黑体, Arial, Tahoma, sans-serif, serif;">ttributedString,</span>