UITextView添加超鏈接及屏蔽選中復(fù)制

由于業(yè)務(wù)需要搞個(gè)文字跳轉(zhuǎn)網(wǎng)頁,網(wǎng)上的版本很多都很復(fù)雜,記錄個(gè)簡(jiǎn)單版本的.

1.首先創(chuàng)建個(gè)UITextView的子類.

如果需要滑動(dòng)View可以把-(void)addGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer注釋取消.

@implementation UITextLinkView: UITextView

- (BOOL)canBecomeFirstResponder
{
    return NO;
}

- (UITextRange *)selectedTextRange{
    return nil;
}

-(void)addGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer{
   取消所有手勢(shì),如果需要其他的可以打開注釋.
   //  if ([gestureRecognizer isKindOfClass:[UILongPressGestureRecognizer class]] ) {
     //   gestureRecognizer.enabled = NO;
   //}
   // [super addGestureRecognizer:gestureRecognizer];
}
@end

2.創(chuàng)建textView

_detailTextView = [UITextLinkView new]; 
_detailTextView.textAlignment = NSTextAlignmentLeft;
// 修改可點(diǎn)擊文字的顏色
    _detailTextView.linkTextAttributes = @{NSForegroundColorAttributeName:[UIColor redColor],NSUnderlineStyleAttributeName:@(1)}; 
    _detailTextView.editable = NO;
    _detailTextView.scrollEnabled = NO;
//讓textVIew文字內(nèi)容邊距為0,便于設(shè)置約束.
    _detailTextView.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0);

3.添加文字

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
 paragraphStyle.lineSpacing = 2; // 行間距
NSString * contentStr = @"啦啦啦";
 NSString * jumpStr = @"點(diǎn)我跳轉(zhuǎn)";
NSString * urlStr = @"http://www.baidu.com";
 contentStr = [ contentStr stringByAppendingString:jumpStr];
//這步是防止點(diǎn)擊鏈接后如果沒有文字,那么點(diǎn)擊textVIew后面的空白區(qū)域也會(huì)跳轉(zhuǎn)
   contentStr = [ contentStr stringByAppendingString:@" "];
 NSDictionary *attributes = @{
 NSForegroundColorAttributeName:[UIColor blackColor],
 NSParagraphStyleAttributeName:paragraphStyle};
 NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithString:contentStr attributes:attributes];
//添加跳轉(zhuǎn)文字及跳轉(zhuǎn)鏈接
         [attrStr addAttribute:NSLinkAttributeName value:urlStr range:[contentStr rangeOfString:jumpStr]];
 _detailTextView.attributedText = attrStr;
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1、通過CocoaPods安裝項(xiàng)目名稱項(xiàng)目信息 AFNetworking網(wǎng)絡(luò)請(qǐng)求組件 FMDB本地?cái)?shù)據(jù)庫組件 SD...
    陽明AI閱讀 16,172評(píng)論 3 119
  • 生活在這個(gè)世界,我們?cè)诓煌哪挲g、不同的人生階段,有著不相同的狀態(tài)與心理變化,這些狀態(tài)和心理變化,會(huì)左右我...
    舒心主兒閱讀 516評(píng)論 0 2
  • 夢(mèng)魘再深也終會(huì)醒 而現(xiàn)實(shí)生活不會(huì)醒 恰好相反 醒著就是沉睡 徹底沉睡才會(huì)醒 ??? 浮生若夢(mèng) 美也似夢(mèng) 噩也似夢(mèng) ???
    米酒姑娘閱讀 305評(píng)論 0 3
  • 2017.9.18。無為。焦點(diǎn)解決,分享第61天。我很欣賞下面的文字: 快樂是什么?快樂就是一種心理上...
    無為wyw閱讀 583評(píng)論 0 1

友情鏈接更多精彩內(nèi)容