zoukankan      html  css  js  c++  java
  • 给UITextView添加链接

    给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 
  • 相关阅读:
    第5.3课.多输入之多线程和fork
    第5.2课多输入之select
    第5.1课,多输入之轮询
    第4课.编写通用的Makefile
    第3课.电子书框架
    2.3freetype矢量字体
    建立u-boot,内核的SI工程
    2.1/2.2字符的编码方式及显示
    1.0数码相框框架分析
    [数据结构]一些有意思题目(一)
  • 原文地址:https://www.cnblogs.com/W-Kr/p/5095296.html
Copyright © 2011-2022 走看看