代码库> 文字视图> NSMutableAttributedString给UITextView 添加超链接
NSMutableAttributedString给UITextView 添加超链接
关注
上传者:郭鹏飞 分类:文字视图(Textview)
查看次数:5091 下载次数:384
上传时间: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


本周热门下载
综合评论
提示
sina weixin mail 回到顶部