• 给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 
  • 相关阅读:
    mybatis中大于等于小于等于的写法
    RandomAccess接口
    ArrayList源码解析
    使用Docker搭建MySQL主从复制(一主一从)
    狂神Docker视频学习笔记(基础篇)
    【JQ】jQuery实现将div中滚动条滚动到指定位置的方法
    JAVA线程池的基本使用
    史上最全的Java技术体系思维导图,没有之一!
    springboot整合kafka
    spring cloud alibaba 分布式事务解决方案之seata-1.3.0
  • 原文地址:https://www.cnblogs.com/W-Kr/p/5095296.html
Copyright © 2020-2023  润新知