在NSString中 添加URL 图片




今天一天都在忙着给  NSString 中部分内容添加URL,可以给一个NSAttributedString增加链接了,然后当它被点击的时候唤起一个定制的action。
 
首先,创建一个NSAttributedString然后增加给它增加一个NSLinkAttributeName 属性,见以下:
 
 
  1. NSString * str = [NSString stringWithFormat:@"This is an example by @网页链接"];

        NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:str];

        NSRange urlRange = [str rangeOfString:@"@网页链接"];

        [string addAttribute:NSLinkAttributeName

                       value:@"http://m.baidu.com"

                       range:urlRange];

        [string addAttribute:NSForegroundColorAttributeName

                       value:[UIColor blueColor]

                       range:urlRange];

        [string endEditing];

        

        

        UITextView * textView = [[UITextView alloc] initWithFrame:CGRectMake(100, 50, 200, 200)];

        textView.backgroundColor =[UIColor whiteColor];

        textView.delegate = self;

        [textView setSelectable: YES];

        [textView setEditable:NO];

        textView.attributedText = string;

        textView.dataDetectorTypes = UIDataDetectorTypeLink;

        [self.view addSubview:textView];

 
这样就可以让链接在文本中显示。然而,你也可以控制当链接被点击的时候会发生什么,实现这个可以使用UITextViewDelegate协议的新的shouldInteractWithURL方法,就像这样:
 
 
  1. - (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {

        NSLog(@"%@",URL);

       

      UIWebView *web = [[UIWebView alloc] initWithFrame:CGRectMake(0, 100, 375, 500)];

        NSURLRequest *request = [NSURLRequest requestWithURL:URL];

        [web loadRequest:request];

        [self.view addSubview:web];

        

    //    return YES;  //系统会用浏览器打开链接

        return NO;

    }

 

第二次编辑,产品要加图片。。。。



 NSTextAttachment *textAttachment = [[NSTextAttachment alloc] initWithData:nil ofType:nil] ;
                textAttachment.image = [UIImage imageNamed:@"icon2"]; //要添加的图片
                NSAttributedString *textAttachmentString = [NSAttributedString attributedStringWithAttachment:textAttachment] ;
                [mut insertAttributedString:textAttachmentString atIndex:string.length-4];//index为用户指定要插入图片的位置,mut 是原来的a<span style="font-family: 'Helvetica Neue', Helvetica, STheiti, 微软雅黑, 黑体, Arial, Tahoma, sans-serif, serif;">ttributedString,</span>



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值