这篇文章主要给大家介绍了关于iOS中添加文本链接和图片的相关资料,文中通过示例代码介绍的非常详细,对大家具有一定的参考学习价值,需要的朋友们下面跟着小编一起来学习学习吧。
前言
我们在开发过程中会遇到这样的需求。用户注册,或者做些其他操作的时候我们需要在下方加上这样一段话:注册代表你遵守我们的《用户协议》,《隐私条款》这两个是链接,那么接下来我们改怎么做呢,下面来一起看看详细的介绍:
先上图再说话
实现方法
如果我们按照平常的想法在label上面显示文字,然后给label加上手势也可以实现,那么链接多的话,你就要判断点击手势的区域,感觉麻烦,那么苹果给我们提供了很好的方法富文本NSMutableAttributedString。
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在
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
return YES;
}
代理方法里面做你想要的操作,可是呢,有时后文字是分条显示的 第一条,第二条,但是又不让用文字,而是用上面的小点图片显示的,这就需要插入图片了
//文本插入图片
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];
富文本里面还有好多东西,有兴趣的小伙伴可以研究一下
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如有疑问大家可以留言交流,谢谢大家对编程学习网的支持。
本文标题为:iOS中添加文本链接和图片示例代码
- 最好用的ios数据恢复软件:PhoneRescue for Mac 2023-09-14
- SurfaceView播放视频发送弹幕并实现滚动歌词 2023-01-02
- Android实现监听音量的变化 2023-03-30
- Flutter实现底部和顶部导航栏 2022-08-31
- 作为iOS开发,这道面试题你能答出来,说明你基础很OK! 2023-09-14
- Android MaterialButton使用实例详解(告别shape、selector) 2023-06-16
- Android studio实现动态背景页面 2023-05-23
- 详解flutter engine 那些没被释放的东西 2022-12-04
- iOS 对当前webView进行截屏的方法 2023-03-01
- Android实现轮询的三种方式 2023-02-17
