码迷,mamicode.com
首页 > 移动开发 > 详细

IOS -->> 给UITextView增加链接

时间:2015-09-27 22:53:56      阅读:295      评论:0      收藏:0      [点我收藏+]

标签:

现在在iOS添加你自己的Twitter账户更加简单了,现在你可以给一个NSAttributedString增加链接了,然后当它被点击的时候唤起一个定制的action。
首先,创建一个NSAttributedString然后增加给它增加一个NSLinkAttributeName 属性,见以下:
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"This is an example by @marcelofabri_"]; 
[attributedString addAttribute:NSLinkAttributeName 
                         value:@"username://marcelofabri_" 
                         range:[[attributedString string] rangeOfString:@"@marcelofabri_"]]; 
  
  
NSDictionary *linkAttributes = @{NSForegroundColorAttributeName: [UIColor greenColor], 
                                 NSUnderlineColorAttributeName: [UIColor lightGrayColor], 
                                 NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)}; 
  
// assume that textView is a UITextView previously created (either by code or Interface Builder) 
textView.linkTextAttributes = linkAttributes; // customizes the appearance of links 
textView.attributedText = attributedString; 
textView.delegate = self; 

 

这样就可以让链接在文本中显示。然而,你也可以控制当链接被点击的时候会发生什么,实现这个可以使用UITextViewDelegate协议的新的shouldInteractWithURL方法,就像这样:

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange { 
    if ([[URL scheme] isEqualToString:@"username"]) { 
        NSString *username = [URL host];  
        // do something with this username 
        // ... 
        return NO; 
    } 
    return YES; // let the system open this URL 
} 

 

IOS -->> 给UITextView增加链接

标签:

原文地址:http://www.cnblogs.com/guojing1991/p/4842876.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!