这篇文章主要给大家介绍了关于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开发教程之XLForm的基本使用方法 2023-05-01
- Android中的webview监听每次URL变化实例 2023-01-23
- Flutter绘图组件之CustomPaint使用详解 2023-05-12
- IOS应用内跳转系统设置相关界面的方法 2022-11-20
- Android多返回栈技术 2023-04-15
- android studio按钮监听的5种方法实例详解 2023-01-12
- 解决Android Studio突然不显示logcat日志的问题 2023-02-04
- Flutter手势密码的实现示例(附demo) 2023-04-11
- IOS 播放系统提示音使用总结(AudioToolbox) 2023-03-01
- Android开发使用RecyclerView添加点击事件实例详解 2023-06-15
