环境:XCode12.3 - IOS14.3
语言:Objective-C
副标题为富文本实现的文字+链接
带链接的富文本只能使用 UITextView,使用 UILabel 无法完全自定义样式与点击事件。
有几个注意点:
@"protocol://"
,可以看到这是一个只有协议名的 URL,我们后面会用到这个协议名。(这个名字随意定即可)// 构造 UITextView
UITextView *textView = [UITextView new]; // 记得配一下 frame,或者用 masonry 布局
textView.editable = NO;
textView.delegate = self; // 记得配置代理
// 构造富文本
NSMutableAttributedString *subTitleString = [[NSMutableAttributedString alloc]
initWithString:@"Payments are secured using the latest industry standards."
attributes:@{
NSForegroundColorAttributeName:UIColor.ibu_tertiaryBlack
}
];
NSMutableAttributedString *urlString = [[NSMutableAttributedString alloc]
initWithString:[NSString stringWithFormat:@" Learn more"]];
[urlString addAttribute:NSLinkAttributeName value:@"protocol://" range:NSMakeRange(0, urlString.length)];
[subTitleString appendAttributedString:urlString];
textView.linkTextAttributes = @{ // 单独在 UITextView 设置链接的颜色与字体
NSFontAttributeName: [NSAttributedString attributedDictionaryWithFontWeight:IBUFontWeight_Regular size:IBUFontSize_Caption_12],
NSForegroundColorAttributeName : UIColor.ibu_brandingBlue
};
textView.attributedText = subTitleString;
注意:此处代码只给出与富文本相关的部分,其它 UI 配置请根据情况自行处理。
UITextView 有链接点击的代理方法,UILabel 没有,这是不能使用 UILabel 的另一个原因。
对代理方法的配置:
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
if ([[URL scheme] isEqualToString:@"protocol"]) { // 找到我们之前设置的协议名
// do your job here
return NO;
}
return YES;
}
希望有所帮助。