现在的位置: 首页 > 综合 > 正文

给UITextView增加链接

2017年10月31日 ⁄ 综合 ⁄ 共 1468字 ⁄ 字号 评论关闭
给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 
 

抱歉!评论已关闭.