溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何在iOS中添加文本鏈接

發(fā)布時(shí)間:2021-04-09 16:50:34 來源:億速云 閱讀:179 作者:Leah 欄目:移動(dòng)開發(fā)

這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)碛嘘P(guān)如何在iOS中添加文本鏈接,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

實(shí)現(xiàn)方法

如果我們按照平常的想法在label上面顯示文字,然后給label加上手勢(shì)也可以實(shí)現(xiàn),那么鏈接多的話,你就要判斷點(diǎn)擊手勢(shì)的區(qū)域,感覺麻煩,那么蘋果給我們提供了很好的方法富文本NSMutableAttributedString。

 UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 100, 375, 100)];
 textView.backgroundColor = [UIColor cyanColor];
 //創(chuàng)建初始化文本的顏色,以及字體大小
 NSDictionary *dictionary = @{NSFontAttributeName:[UIFont systemFontOfSize:17],NSForegroundColorAttributeName:[UIColor yellowColor]};

 NSString * string = @" 跳轉(zhuǎn)到百度\n\n 跳轉(zhuǎn)到簡(jiǎn)書";
 //創(chuàng)建富文本
 NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:string attributes:dictionary];
 //實(shí)現(xiàn)文本鏈接
 [attributeStr addAttribute:NSLinkAttributeName value:@"http://www.jianshu.com" range:[string rangeOfString:@"簡(jiǎn)書"]];
 [attributeStr addAttribute:NSLinkAttributeName value:@"http://www.baidu.com" range:[string rangeOfString:@"百度"]];
// textView.tintColor = [UIColor redColor];//調(diào)節(jié)文本鏈接字體的顏色

 textView.attributedText = attributeStr;
 textView.editable = NO;

上面的方法基本事件點(diǎn)擊點(diǎn)解跳轉(zhuǎn)的功能,當(dāng)然你也可以遵守textview的delegate在

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange

 return YES;
}

代理方法里面做你想要的操作,可是呢,有時(shí)后文字是分條顯示的 第一條,第二條,但是又不讓用文字,而是用上面的小點(diǎn)圖片顯示的,這就需要插入圖片了

 //文本插入圖片
 NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
 attachment.image = [UIImage imageNamed:@"red_2"];
 //圖片大小不合適 可以調(diào)整
 attachment.bounds = CGRectMake(0, 0, 8, 8);
 NSMutableAttributedString *attachmentString = (NSMutableAttributedString *)[NSAttributedString attributedStringWithAttachment:attachment];
 //你想要插入圖片的位置
 [textView.textStorage insertAttributedString:attachmentString atIndex:0];
 [textView.textStorage insertAttributedString:attachmentString atIndex:10];

上述就是小編為大家分享的如何在iOS中添加文本鏈接了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

ios
AI