iOS UITextView增加链接 交互

//首先,创建一个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;
textView.editable = NO;   // 非编辑状态下才可以点击Url

这样就可以让链接在文本中显示。然而,你也可以控制当链接被点击的时候会发生什么,实现这个可以使用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 
    } 


例子

     NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc]initWithString:str];
    [attrStr addAttribute:NSLinkAttributeName value:[NSURL URLWithString:@"http://blog.csdn.net/hdfqq188816190/article/details/53556663"] range:[str rangeOfString:@"约炮之旅"]];
    textview.attributedText = attrStr;
    textview.delegate = self;
    textview.editable = NO;   // 非编辑状态下才可以点击Url

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
    return YES;
}



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值