iostext添加点击事件_iOS实现一段文字中指定的某些文字点击有响应事件或者可以跳转(给字符串添加超链接)...
直接上需求,見如下UI圖:
需求是點擊中間的電話(藍色字體部分),可以直接撥打電話。對于這種很長的一段文字中間夾著可以有點擊事件的文字,可以通過下面這種方式解決:
圖中所指的這段文字,不用UILabel來展示,用UITextView來展示,如下:
//富文本
- (UITextView *)bottomTextView {
if (!_bottomTextView) {
_bottomTextView = [[UITextView alloc] init];
_bottomTextView.backgroundColor = [UIColor clearColor];
_bottomTextView.editable = NO;//設置為不可編輯
_bottomTextView.scrollEnabled = NO;
_bottomTextView.delegate = self;//設置代理
_bottomTextView.textContainerInset = UIEdgeInsetsMake(0.f, 0.f, 0.f, 0.f);//控制距離上下左右的邊距
NSString *htmlString = [NSString stringWithFormat:@"放款時將以消息中心和短信通知您,實際到賬時間依賴收款卡銀行處理時間,請注意查收。如果您確認借款一天后仍未收到放款,您可以致電 400-060-8588 咨詢放款進度"];
//HTML格式的文本
NSMutableAttributedString* attributedString = [[NSMutableAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} documentAttributes:nil error:nil];
NSMutableParagraphStyle *style = [attributedString attribute:NSParagraphStyleAttributeName atIndex:0 effectiveRange:nil];
style.alignment = NSTextAlignmentLeft;
_bottomTextView.attributedText = attributedString;
}
return _bottomTextView;
}
這種方案其實利用的就是UITextView可以展示HTML格式的文本,如代碼中的htmlString的值就是拼接的html文本,文本中可以設置點擊的鏈接地址。點擊鏈接會調用UITextView的下面這個代理方法:
#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
//URL:就是那個跳轉鏈接
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%ld",(long)4000608588]]];
//返回NO,如果返回YES就會跳到Safari
return NO;
}
注意:
1、UITextView上下左右默認是有間距的,可以通過textContainerInset屬性來調整。
2、帶鏈接的字體顏色默認是藍色,在HTML文本中設置其他顏色是不生效的,如果想設置帶鏈接的字體顏色可以通過UITextView的linkTextAttributes屬性來設置。
---------------------
作者:大飛哥666
來源:CSDN
原文:https://blog.csdn.net/u013602835/article/details/86691153
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!
總結
以上是生活随笔為你收集整理的iostext添加点击事件_iOS实现一段文字中指定的某些文字点击有响应事件或者可以跳转(给字符串添加超链接)...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 浏览器事件捕获冒泡以及阻止冒泡
- 下一篇: idea 代码第一次上传git_如何使用