前言
在项目中要在展示展示的文字中,自动匹配url 并且点击实现跳转,看了很多第三方的感觉都很复杂。后来自己写了一个简单的。
实现代码如下
1、创建一个继承UITextView的CjTextView 。
import <UIKit/UIKit.h>
@interface CjTextView : UITextView
@end
import "CjTextView.h"
@interface CjTextView ()
@property (nonatomic, copy ) NSString myText;
@property (nonatomic, assign) NSRange urlTange;
@property (nonatomic, copy ) NSString url;
@end
@implementation CjTextView
-(instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
}
return self;
}
// 重写了text的set 方法
-(void)setText:(NSString * )text{
self.myText = text;
[self.textStorage setAttributedString:[[NSAttributedString alloc]initWithString:text]];
NSRange range = NSMakeRange(0, self.myText.length);
[self.textStorage addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:range];
在这个方法中可以改变网址的颜色字体大小等属性。
[self doing];
}
-(void)layoutSubviews{
[super layoutSubviews];
self.textContainer.size = self.bounds.size;
}
-(void)touchesBegan:(NSSet<UITouch *> )touches withEvent:(UIEvent )event{
CGPoint point = [[touches anyObject] locationInView:self];
NSRange range =self.urlTange;
self.selectedRange = range;
NSArray array = [self selectionRectsForRange:self.selectedTextRange];
for (UITextSelectionRect obj in array) {
if (CGRectContainsPoint(obj.rect, point)) {
NSLog(@"你点击了网址%@",_url);
}
}
}
-(void) doing {
NSDataDetector * dataDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingAllTypes error:nil];
NSArray res= [dataDetector matchesInString:self.textStorage.string options:NSMatchingReportProgress range:NSMakeRange(0, self.textStorage.string.length)];
for (NSTextCheckingResultresult in res) {
self.urlTange = result.range;
NSString str = [self.textStorage.string substringWithRange:result.range];
self.url = str;
NSMutableAttributedString *att= [[NSMutableAttributedString alloc]initWithString:str];
[att addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, str.length)];
[att addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(0, str.length)];
[self.textStorage replaceCharactersInRange:result.range withAttributedString:att];
}
}
@end
2、在控制器中实现
include "CjTextView.h"
@interface ViewController ()
@end
@implementation ViewController
(void)viewDidLoad {
[super viewDidLoad];
CjTextView *label = [[CjTextView alloc]init];
关掉弹出键盘
label.editable = NO;
label.text = @"123发送的股份大概放到放到地方多福多寿http://baidu.comuiiyiroiqiotioq" ;
label.backgroundColor = [UIColor yellowColor];
label.frame = CGRectMake(100, 100, 202, 200);;
[self.view addSubview: label];
}
就是这么简单的代码就实现了
总结
以上就是这篇文章的全部内容了,希望本文的内容对各位Android开发者们能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对软件开发网的支持。
您可能感兴趣的文章:android TextView中识别多个url并分别点击跳转方法详解