要实现效果如图:
核心原理:
先将TextView的linkTextAttributes属性设为空值(超链接默认颜色为蓝色,置空后,添加的富文本颜色才会生效),然后给正文添加超链接,颜色设为App字体颜色。再给正文后面追加的展开/收起,也添加超链接,富文本颜色设置为蓝色,借助点击超链接代理方法来判断你点的是哪个部分,再通过block实现对应的功能。
注意TextView的初始属性:
_quickTitleTextV = [[CustomTextView alloc] init];
_quickTitleTextV.font = UISetting_FONT_S(adjustWidth(16));
_quickTitleTextV.textColor = MWTextColor1;
_quickTitleTextV.editable = NO;
_quickTitleTextV.scrollEnabled = NO;
_quickTitleTextV.linkTextAttributes = @{};//核心代码
_quickTitleTextV.delegate = self;
[_quickTitleTextV setTextContainerInset:UIEdgeInsetsZero];
[self.contentView addSubview:_quickTitleTextV];
展开
_quickTitleTextV.text = [NSString stringWithFormat:@"%@...展开", [contentsubstringWithRange:NSMakeRange(0, textNumber)]];
NSInteger textLength = _quickTitleTextV.text.length;
NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:_quickTitleTextV.text];
[attributeStr addAttribute:NSLinkAttributeName value:@"http://click" range:NSMakeRange(0, textLength - 2)];//链接
[attributeStr addAttribute:NSLinkAttributeName value:@"http://expand" range:NSMakeRange(textLength - 2, 2)];//链接
[attributeStr addAttribute:NSForegroundColorAttributeName value:MWTextColorBlue range:NSMakeRange(textLength - 2, 2)];
_quickTitleTextV.attributedText = attributeStr;
收起
_quickTitleTextV.text = [NSString stringWithFormat:@"%@ 收起", content];
NSInteger textLength = _quickTitleTextV.text.length;
NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:_quickTitleTextV.text];
[attributeStr addAttribute:NSLinkAttributeName value:@"http://click" range:NSMakeRange(0, textLength - 2)];//链接
[attributeStr addAttribute:NSLinkAttributeName value:@"http://close" range:NSMakeRange(textLength - 2, 2)];//链接
[attributeStr addAttribute:NSForegroundColorAttributeName value:MWTextColorBlue range:NSMakeRange(textLength - 2, 2)];
_quickTitleTextV.attributedText = attributeStr;
textView代理方法
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
if ([URL.absoluteString containsString:@"click"]) {
if (_textViewDicClickBlock) {
_textViewDicClickBlock();
}
return NO;
}
_model.isExpand = !_model.isExpand;
if (_expandBlock) {
_expandBlock();
}
return NO;
}