代码库> 文字视图> NSMutableAttributedString给UITextView 添加超链接
NSMutableAttributedString给UITextView 添加超链接
关注
上传者:郭鹏飞 分类:文字视图(Textview)
查看次数:5237 下载次数:386
上传时间:2015-07-24 大小:28 B
给UITextView添加超链接  


//
//  ViewController.m
//  Attributed
//
//  Created by XXX on 15/7/24.
//  Copyright (c) 2015年 iOS开发交流196435206. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSString * str = [NSString stringWithFormat:@"This is an example by @www.apple.com/"];
    
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:str]; // assume string exists
    NSRange urlRange = [str rangeOfString:@"www.apple.com/"];
    [string addAttribute:NSLinkAttributeName
                   value:@"username://@www.apple.com/"
                   range:urlRange];
    [string addAttribute:NSForegroundColorAttributeName
                   value:[UIColor blueColor]
                   range:urlRange];
    [string addAttribute:NSUnderlineStyleAttributeName
                   value:@(NSUnderlineStyleNone)
                   range:urlRange];
    [string endEditing];
    
    UITextView * textView = [[UITextView alloc] initWithFrame:CGRectMake(100, 200, 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];
    
}
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
    NSLog(@"url :%@",URL);
    if ([[URL scheme] isEqualToString:@"username"]) {
        NSString *username = [URL host];
        NSLog(@"username :%@",username);
        return NO;
    }
    return YES;
}
@end


测试环境:Xcode 6.2,iOS 6.0 以上
收藏
我来说两句
发表评论
您还没有登录!请登录注册
所有评论(0


本周热门下载
综合评论
  • 下载地址:https://github.com/wangruofeng/RFSegmentView
  • 下载来先帮你修bug,自己锁屏解锁看下,,已经修复好了
    王爸爸 评论了 XYUISlider
  • 没有编辑选项??
    不要再下载这个代码了,github我重构了下,原来业务臃肿垃圾的东西都剔了
  • https://github.com/tianya2416/GKiOSNovel
    tianya2416 评论了 Novel
  • 您好,想实现每类都可以多选该怎么修改呢?
    愤愤忠 评论了 iOS 商品规格选择
  • 去哪里star
    18665920701 评论了 Novel
提示
sina weixin mail 回到顶部