参考:
Swift - 给UITextView添加自定义链接,以及链接的点击响应
import Foundation
import UIKit
extension UITextView {
/// 添加链接文本(链接为空时则表示普通文本),且可加大指导字符串(默认font = 13)
///
/// - Parameters:
/// - string: 文本
/// - increaseStr: 需加大的字符串
/// - withURLString: 链接
/// - lineSpacing: 行间距
func appendLinkString(string:String,
increaseStr:String?,
withURLString:String?,
lineSpacing:CGFloat) {
// 原来的文本内容
let attrString:NSMutableAttributedString = NSMutableAttributedString()
attrString.append(self.attributedText)
// 新增的文本内容(使用默认设置的字体样式)
let attrs = [NSFontAttributeName : self.font!,
NSForegroundColorAttributeName : self.textColor ?? UIColor.black] as [String : Any]
let appendString = NSMutableAttributedString(string: string, attributes:attrs)
let range:NSRange = NSMakeRange(0, appendString.length)
// 判断是否是链接文字
if let urlStr = withURLString {
appendString.beginEditing()
appendString.addAttribute(NSLinkAttributeName, value:urlStr, range:range)
appendString.endEditing()
appendString.addAttribute(NSUnderlineStyleAttributeName, value: NSNumber.init(integerLiteral: NSUnderlineStyle.styleSingle.rawValue), range: range)
}
// 字体加大
if let increase: String = increaseStr {
let tipRange: NSRange = NSString.init(string: string).range(of:increase)
appendString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 13), range: tipRange)
}
// 调整行间距
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineSpacing
appendString.addAttribute(NSParagraphStyleAttributeName,
value: paragraphStyle,
range: range)
// 合并新的文本
attrString.append(appendString)
// 设置合并后的文本
self.attributedText = attrString
}
}
控制器中配置TextView
调用appendLinkString
函数
- (void)configTextView{
self.textView.delegate = self;
NSString *str0 = @"温馨提示:\n\n1.用户使用快捷充值不收取任何手续费。单笔充值限额根据各个银行上的充值限额为准,";
NSString *str1 = @"点击查看银行限额说明";
NSString *str2 = @"。\n";
NSString *str3 = @"2.因为银行会在23:30到次日凌晨3:00进行系统数据处理,请尽量避免在此时间段充值。\n3.如果充值失败,请拨打客服咨询电话400-009-9595。";
[self.textView appendLinkStringWithString:str0
increaseStr:@"温馨提示"
withURLString:nil
lineSpacing:5];
[self.textView appendLinkStringWithString:str1
increaseStr:nil
withURLString:@"look:bankCardLimits"
lineSpacing:5];
[self.textView appendLinkStringWithString:str2
increaseStr:nil
withURLString:nil
lineSpacing:5];
[self.textView appendLinkStringWithString:str3
increaseStr:nil
withURLString:nil
lineSpacing:5];
}
UITextViewDelegate
获取自定义链接Url
,进行事件处理
#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange{
// 查看银行卡限额
if ([URL.scheme isEqualToString:@"look"]) {
}
return YES;
}