UITextView指定文字添加点击事件

指定文字文字添加点击事件,其实就是超链接。
代码如下:

step1:
NSMutableAttributedString * atrStr = [[NSMutableAttributedString alloc] initWithString:@"一二三四,一二三四像首歌,绿色军营."];
[atrStr addAttribute:NSForegroundColorAttributeName
                               value:[UIColor whiteColor]
                               range:NSMakeRange(0, atrStr.length - 5)];
[atrStr addAttribute:NSBaselineOffsetAttributeName
                               value:[NSNumber numberWithFloat:-4]
                               range:NSMakeRange(0, atrStr.length)];
[atrStr addAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
//                              [NSNumber numberWithInt:1],NSUnderlineStyleAttributeName,   // 下划线
                                [NSNumber numberWithFloat:-5],NSBaselineOffsetAttributeName, // 基线偏移,负值:向下偏移
                                [UIFont boldSystemFontOfSize:13.0], NSFontAttributeName,
                                [NSURL URLWithString:@"www.baidu.com"], NSLinkAttributeName,
                                nil] range:NSMakeRange(atrStr.length - 5, 4)];
textV.linkTextAttributes = @{NSForegroundColorAttributeName : [UIColor blackColor]};
textV.attributedText = atrStr;
textV.textAlignment = NSTextAlignmentCenter;
textV.delegate = self;
textV.editable = NO;

设置基线偏移 是因为textview文字靠上,所以通过偏移使其水平居中。
哦对了,textV就是一个普通的UITextView创建及设置frame就不多说了。

Step2:

添加超链接之后的点击事件:

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
    // 这里写想要进行的操作 譬如:push到某个页面...
    return YES;
}

补充一些其他的属性:

// 这些属性对应的数据类型请参考官方文档
NSObliquenessAttributeName  字体倾斜程度
NSBackgroundColorAttributeName   文字的背景色,不是文字的颜色
NSForegroundColorAttributeName  文字颜色
NSKernAttributeName  文字间距
NSStrikethroughStyleAttributeName  删除线
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,422评论 19 139
  • UIWindow 初始化: self.window= [[UIWindowalloc]initWithFrame:...
    Sunny_Fight阅读 4,657评论 0 1
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,216评论 4 61
  • 期中考试结束,今天学校组织开家长会,家长们早早来到教室,无一缺席,积极性很高!找到孩子的座位,首先看到了宝贝的...
    孙嘉润妈妈阅读 1,241评论 0 0
  • 两条惊恐的鱼 吐出海洋的秘密 我用脆弱的杯子接水 喝了又喝 还是觉得口渴 有时候憋闷的无法呼吸 有时候想点一支蜡烛...
    苏拉曼神阅读 2,548评论 2 2