您好,登錄后才能下訂單哦!
前言
在項(xiàng)目中要在展示展示的文字中,自動(dòng)匹配url 并且點(diǎn)擊實(shí)現(xiàn)跳轉(zhuǎn),看了很多第三方的感覺都很復(fù)雜。后來自己寫了一個(gè)簡單的。
實(shí)現(xiàn)代碼如下
1、創(chuàng)建一個(gè)繼承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]; 在這個(gè)方法中可以改變網(wǎng)址的顏色字體大小等屬性。 [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(@"你點(diǎn)擊了網(wǎng)址%@",_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、在控制器中實(shí)現(xiàn)
include "CjTextView.h" @interface ViewController () @end @implementation ViewController (void)viewDidLoad { [super viewDidLoad]; CjTextView *label = [[CjTextView alloc]init];
關(guān)掉彈出鍵盤
label.editable = NO; label.text = @"123發(fā)送的股份大概放到放到地方多福多壽http://baidu.comuiiyiroiqiotioq" ; label.backgroundColor = [UIColor yellowColor]; label.frame = CGRectMake(100, 100, 202, 200);; [self.view addSubview: label]; }
就是這么簡單的代碼就實(shí)現(xiàn)了
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對各位Android開發(fā)者們能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對億速云的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。