在TextHighlight的属性 .userInfo 中保存有数据,如何在label.highlightTapAction = { (containerView, text, range, rect) in }回调中获取到?
Opened this issue · 4 comments
L2Mlee commented
使用BSLabel做高亮点击时, TextHighlight的uerInfo中保存有数据,但在BSLabel的高亮点击会回调中,获取不到BSLabel的TextHighlight对象(private)的属性, 也就获取不到uerInfo。
YYText中是可以这样的:
_commentLabel.highlightTapAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
// 利用KVC获取UserInfo
YYTextHighlight *highlight = [containerView valueForKeyPath:@"_highlight"];
// 拿到 highlight.userInfo中的数据
};
a1049145827 commented
Swift语言特性貌似不支持这么操作,下面样例代码可以支持你的需求吗?
let highlight = TextHighlight()
highlight.border = border
highlight.tapAction = { [weak self] containerView, text, range, rect in
self?.showMessage("Tap: \((text?.string as NSString?)?.substring(with: range) ?? "")")
// 外部数据直接在block中使用
highlight.xxx
}
one.bs_set(textHighlight: highlight, range: one.bs_rangeOfAll)
1071273821 commented
楼主的意思并不一定要设置userInfo,关键是tapAction回调的range是不靠谱的,多个range时,需要每个range对应一个Any对象(我们传给你,tap时再回调过来)来准确区分用户点击的数据,这一点是缺乏的,希望作者能够完善一下,谢谢了
aidevjoe commented
linkAttrString.bs_set(textHighlightRange: NSRange(location: 0, length: content.count), color: .link, backgroundColor: .link, userInfo: ["url": urlString], tapAction: { v, attrString, range, _ in
guard let highlight = attrString?.bs_attribute(NSAttributedString.Key(TextAttribute.textHighlightAttributeName), at: range.location),
let url = (highlight as? TextHighlight)?.userInfo?["url"] as? String else { return }
log.verbose(url)
}, longPress: nil)
a1049145827 commented
楼主的意思并不一定要设置userInfo,关键是tapAction回调的range是不靠谱的,多个range时,需要每个range对应一个Any对象(我们传给你,tap时再回调过来)来准确区分用户点击的数据,这一点是缺乏的,希望作者能够完善一下,谢谢了
tapAction回调的range是highlight在整个attrString的range,这个值是正确的
参考这种写法:
linkAttrString.bs_set(textHighlightRange: NSRange(location: 0, length: content.count), color: .link, backgroundColor: .link, userInfo: ["url": urlString], tapAction: { v, attrString, range, _ in guard let highlight = attrString?.bs_attribute(NSAttributedString.Key(TextAttribute.textHighlightAttributeName), at: range.location), let url = (highlight as? TextHighlight)?.userInfo?["url"] as? String else { return } log.verbose(url) }, longPress: nil)