要實現(xiàn)效果如圖:
IMG_3792.PNG
IMG_3793.PNG
核心原理:
先將TextView的linkTextAttributes屬性設(shè)為空值(超鏈接默認(rèn)顏色為藍(lán)色菩鲜,置空后,添加的富文本顏色才會生效)惦积,然后給正文添加超鏈接接校,顏色設(shè)為App字體顏色。再給正文后面追加的展開/收起狮崩,也添加超鏈接蛛勉,富文本顏色設(shè)置為藍(lán)色,借助點(diǎn)擊超鏈接代理方法來判斷你點(diǎn)的是哪個部分睦柴,再通過block實現(xiàn)對應(yīng)的功能诽凌。
注意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;
}