首页 > 其他 > 详细

给UITextView添加链接

时间:2016-01-02 22:33:48      阅读:193      评论:0      收藏:0      [点我收藏+]
给UITextView增加了链接
现在在iOS添加你自己的Twitter账户更加简单了,现在你可以给一个NSAttributedString增加链接了,然后当它被点击的时候唤起一个定制的action。
 
首先,创建一个NSAttributedString然后增加给它增加一个NSLinkAttributeName 属性,见以下:
  1. NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"This is an example by @marcelofabri_"]; 
  2. [attributedString addAttribute:NSLinkAttributeName 
  3.                          value:@"username://marcelofabri_" 
  4.                          range:[[attributedString string] rangeOfString:@"@marcelofabri_"]]; 
  5.   
  6.   
  7. NSDictionary *linkAttributes = @{NSForegroundColorAttributeName: [UIColor greenColor], 
  8.                                  NSUnderlineColorAttributeName: [UIColor lightGrayColor], 
  9.                                  NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)}; 
  10.   
  11. // assume that textView is a UITextView previously created (either by code or Interface Builder) 
  12. textView.linkTextAttributes = linkAttributes; // customizes the appearance of links 
  13. textView.attributedText = attributedString; 
  14. textView.delegate = self; 
 
这样就可以让链接在文本中显示。然而,你也可以控制当链接被点击的时候会发生什么,实现这个可以使用UITextViewDelegate协议的新的shouldInteractWithURL方法,就像这样:
  1. - (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange { 
  2.     if ([[URL scheme] isEqualToString:@"username"]) { 
  3.         NSString *username = [URL host];  
  4.         // do something with this username 
  5.         // ... 
  6.         return NO; 
  7.     } 
  8.     return YES; // let the system open this URL 

给UITextView添加链接

原文:http://www.cnblogs.com/W-Kr/p/5095296.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!