一、點(diǎn)擊到轉(zhuǎn)到網(wǎng)頁(yè)類(lèi)型
如下代碼:
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"這是一段可點(diǎn)擊的文字,點(diǎn)擊百度去瀏覽網(wǎng)頁(yè)吧"];
[attributedString addAttribute:NSLinkAttributeName
value:@"https://www.baidu.com"
range:[[attributedString string] rangeOfString:@"百度"]];
[attributedString addAttribute:NSFontAttributeName
value:[UIFont systemFontOfSize:20]
range:NSMakeRange(0, attributedString.length)];
self.textview.attributedText = attributedString;
self.textview.linkTextAttributes = @{NSForegroundColorAttributeName: [UIColor blueColor], NSUnderlineColorAttributeName: [UIColor lightGrayColor],NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)};
因?yàn)槭鞘褂胻extView來(lái)顯示的,所以要把textView的editable
和scrollEnabled
設(shè)置為NO
.效果如下:
AC8AFABA23F47807D1F314EFB0304BB1.png
IMG_1702.PNG
二、執(zhí)行自定義點(diǎn)擊事件類(lèi)型
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"這是一段可點(diǎn)擊的文字呵恢,點(diǎn)擊百度去瀏覽網(wǎng)頁(yè)吧,當(dāng)然你也可以點(diǎn)擊自定義來(lái)執(zhí)行用戶(hù)事件!"];
[attributedString addAttribute:NSLinkAttributeName
value:@"https://www.baidu.com"
range:[[attributedString string] rangeOfString:@"百度"]];
[attributedString addAttribute:NSLinkAttributeName
value:@"CustomTapEvents://"
range:[[attributedString string] rangeOfString:@"自定義"]];
[attributedString addAttribute:NSFontAttributeName
value:[UIFont systemFontOfSize:20]
range:NSMakeRange(0, attributedString.length)];
self.textview.attributedText = attributedString;
self.textview.linkTextAttributes = @{NSForegroundColorAttributeName: [UIColor blueColor],
NSUnderlineColorAttributeName: [UIColor lightGrayColor],
NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)};
self.textview.delegate = self;
self.textview.editable = NO;
self.textview.scrollEnabled = NO;
代理方法:
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
if ([[URL scheme] isEqualToString:@"CustomTapEvents"]) {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"用戶(hù)點(diǎn)擊了自定義事件" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleCancel handler:nil];
[alertController addAction:action];
[self presentViewController:alertController animated:YES completion:nil];
return NO;
}
return YES;
}
效果圖:
IMG_1703.PNG
如有不足之處媚创,還請(qǐng)多多指教渗钉。