前言
10年積累的網(wǎng)站建設(shè)、網(wǎng)站設(shè)計經(jīng)驗,可以快速應(yīng)對客戶對網(wǎng)站的新想法和需求。提供各種問題對應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識你,你也不認(rèn)識我。但先制作網(wǎng)站后付款的網(wǎng)站建設(shè)流程,更有措美免費網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。在項目中要在展示展示的文字中,自動匹配url 并且點擊實現(xiàn)跳轉(zhuǎn),看了很多第三方的感覺都很復(fù)雜。后來自己寫了一個簡單的。
實現(xiàn)代碼如下
1、創(chuàng)建一個繼承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]; 在這個方法中可以改變網(wǎng)址的顏色字體大小等屬性。 [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(@"你點擊了網(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