本文只對富文本中部分文字添加點(diǎn)擊事件做簡單介紹
1.添加點(diǎn)擊事件
YYLabel中給部分文字添加點(diǎn)擊事件主要是在富文本排版的時(shí)候,創(chuàng)建YYTextHighlight對象,設(shè)置Range,并可以可以給他賦值一個(gè)JSON字典以便在之后點(diǎn)擊文本之后可以獲取到內(nèi)容(如@{@"action":@"comment"}).
設(shè)置YYTextHighlight的時(shí)候同時(shí)可以設(shè)置YYTextBorder,也就是背景顏色以及圓角等等,再點(diǎn)擊的時(shí)候看起來不會(huì)顯得空洞,有直觀的反饋
設(shè)置富文本的代碼如下
NSString *showStr = @"我有一頭小毛驢,從來也不騎~~";
NSMutableAttributedString *authorSayAtt = [[NSMutableAttributedString alloc] initWithString:showStr];
[authorSayAtt setColor:[UIColor blackColor]];
//YYTextBorder設(shè)置點(diǎn)擊的背景顏色,圓角
YYTextBorder *textBoder = [YYTextBorder new];
textBoder.insets = UIEdgeInsetsMake(0, 0, 0, 0);
textBoder.cornerRadius = 5;
textBoder.fillColor = UIColorFromRGB(0xd7d7d7);
//給文字設(shè)置Highlight
YYTextHighlight *hightLight = [YYTextHighlight new];
[hightLight setBackgroundBorder:textBoder];
[authorSayAtt setTextHighlight:hightLight range:[showStr rangeOfString:@"毛驢"]];
YYTextContainer *container = [[YYTextContainer alloc] init];
container.size = CGSizeMake(windWidth-kReaderLeftSpace*2, CGFLOAT_MAX);
YYTextLayout *layout = [YYTextLayout layoutWithContainer:container text:authorSayAtt];
//此處的YYTextLayout可以計(jì)算富文本的高度,他有一個(gè)屬性textBoundingRect和textBoundingSize,container.size是用來限制寬度的,可以計(jì)算高度
//YYTextLayout是用來賦值給YYLabel,相當(dāng)于UILabel的attributedText
//如果單純的做點(diǎn)擊處理可以用attributedText直接賦值給YYLabel,但是如果需要異步渲染就必須用YYTextLayout
然后在初始化YYLabel的地方,調(diào)用YYLabel的highlightTapAction屬性就可以獲取到點(diǎn)擊的區(qū)域,文本信息等
-(YYLabel *)authorSayLabel
{
if (!_authorSayLabel) {
_authorSayLabel = [[YYLabel alloc] init];
_authorSayLabel.highlightTapAction = ^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
YYLabel *useLabel = (YYLabel *)containerView;
NSAttributedString *attribute = useLabel.textLayout.text;
if (range.location >= text.length) {
return ;
}
YYTextHighlight *heightLight = [attribute attribute:YYTextHighlightAttributeName atIndex:range.location];
NSDictionary *dic = heightLight.userInfo;
DLog(@"攜帶的值===%@",dic);
//此處的dic,就是之前設(shè)置富文本時(shí)的字典
};
}
return _authorSayLabel;
}
2.關(guān)于YYLabel設(shè)置點(diǎn)擊事件不響應(yīng)的問題,主要有幾個(gè)方面
(1).頁面是否有其他的手勢,例如UITapGestureRecognizer,如果有,需要設(shè)置其屬性cancelsTouchesInView和delaysTouchesBegan都為NO
(2).YYLabel是否添加在了滑動(dòng)視圖上面,如果是需要設(shè)置滑動(dòng)視圖的屬性delaysContentTouches為NO(canCancelContentTouches默認(rèn)為YES,不需改動(dòng))
(3).YYLabel添加在了滑動(dòng)視圖上(如UIScrollVIew上),并且滑動(dòng)視圖上還有UITapGestureRecognizer手勢,這個(gè)時(shí)候需要同時(shí)設(shè)置以上設(shè)置的三個(gè)屬性,否則有一種奇怪現(xiàn)象,點(diǎn)擊文字的時(shí)候如果輕點(diǎn)會(huì)先走UITapGestureRecognizer的方法,再走YYLabel的highlightTapAction點(diǎn)擊事件(右或者不走),稍用力點(diǎn)擊才能夠正常先走YYLabel的highlightTapAction,再觸發(fā)UITapGestureRecognizer的事件方法