iOS中添加文本链接和图片示例代码

时间:2022-09-18 15:54:01

前言

我们在开发过程中会遇到这样的需求。用户注册,或者做些其他操作的时候我们需要在下方加上这样一段话:注册代表你遵守我们的《用户协议》,《隐私条款》这两个是链接,那么接下来我们改怎么做呢,下面来一起看看详细的介绍:

先上图再说话

iOS中添加文本链接和图片示例代码

实现方法

如果我们按照平常的想法在label上面显示文字,然后给label加上手势也可以实现,那么链接多的话,你就要判断点击手势的区域,感觉麻烦,那么苹果给我们提供了很好的方法富文本nsmutableattributedstring。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
uitextview *textview = [[uitextview alloc] initwithframe:cgrectmake(0, 100, 375, 100)];
 textview.backgroundcolor = [uicolor cyancolor];
 //创建初始化文本的颜色,以及字体大小
 nsdictionary *dictionary = @{nsfontattributename:[uifont systemfontofsize:17],nsforegroundcolorattributename:[uicolor yellowcolor]};
 
 nsstring * string = @" 跳转到百度\n\n 跳转到简书";
 //创建富文本
 nsmutableattributedstring *attributestr = [[nsmutableattributedstring alloc] initwithstring:string attributes:dictionary];
 //实现文本链接
 [attributestr addattribute:nslinkattributename value:@"http://www.jianshu.com" range:[string rangeofstring:@"简书"]];
 [attributestr addattribute:nslinkattributename value:@"http://www.baidu.com" range:[string rangeofstring:@"百度"]];
// textview.tintcolor = [uicolor redcolor];//调节文本链接字体的颜色
 
 textview.attributedtext = attributestr;
 textview.editable = no;

上面的方法基本事件点击点解跳转的功能,当然你也可以遵守textview的delegate在

?
1
2
3
4
- (bool)textview:(uitextview *)textview shouldinteractwithurl:(nsurl *)url inrange:(nsrange)characterrange
 
 return yes;
}

代理方法里面做你想要的操作,可是呢,有时后文字是分条显示的 第一条,第二条,但是又不让用文字,而是用上面的小点图片显示的,这就需要插入图片了

?
1
2
3
4
5
6
7
8
9
//文本插入图片
nstextattachment *attachment = [[nstextattachment alloc] init];
attachment.image = [uiimage imagenamed:@"red_2"];
//图片大小不合适 可以调整
attachment.bounds = cgrectmake(0, 0, 8, 8);
nsmutableattributedstring *attachmentstring = (nsmutableattributedstring *)[nsattributedstring attributedstringwithattachment:attachment];
//你想要插入图片的位置
[textview.textstorage insertattributedstring:attachmentstring atindex:0];
[textview.textstorage insertattributedstring:attachmentstring atindex:10];

富文本里面还有好多东西,有兴趣的小伙伴可以研究一下

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如有疑问大家可以留言交流,谢谢大家对服务器之家的支持。

原文链接:http://www.jianshu.com/p/6b018d9895a4