新网创想网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

Android中TextView自动识别url且实现点击跳转-创新互联

前言

10年积累的网站建设、网站设计经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先制作网站后付款的网站建设流程,更有措美免费网站建设让你可以放心的选择与我们合作。

在项目中要在展示展示的文字中,自动匹配url 并且点击实现跳转,看了很多第三方的感觉都很复杂。后来自己写了一个简单的。


实现代码如下


1、创建一个继承UITextView的CjTextView 。

import 

@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 )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

网站名称:Android中TextView自动识别url且实现点击跳转-创新互联
本文地址:http://www.wjwzjz.com/article/dgogpi.html
在线咨询
服务热线
服务热线:028-86922220
TOP