我一直在研究你的问题,这是我的结果,
首先你需要修改库中的JSQMessagesCellTextView并添加一个方法来帮助你检测自定义链接,比如#test,如果你愿意,你可以克隆我的fork并添加这个功能,这就是它的外观,动画问题是因为我的gif转换器
已编辑
https://github.com/rmelian2014/JSQMessagesViewController/tree/contributing
- (void)detectCustomLinks
{
NSMutableArray<NSTextCheckingResult*> *textCheckingResults = [NSMutableArray<NSTextCheckingResult*> array];
for (NSRegularExpression *exp in [self.regularExpressionsDelegate getRegularExpressions]) {
NSArray<NSTextCheckingResult*> * matches = [exp matchesInString:self.text options:NSMatchingWithoutAnchoringBounds range:NSMakeRange(0, self.text.length)];
[textCheckingResults addObjectsFromArray:matches];
}
NSMutableAttributedString * str2 = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
[str2 removeAttribute:NSLinkAttributeName range:NSMakeRange(0, str2.string.length)];
for (NSTextCheckingResult * match in textCheckingResults) {
[str2 addAttribute: NSLinkAttributeName value:[str2 attributedSubstringFromRange:match.range].string range:match.range];
}
self.attributedText = str2;
}
我添加了一个委托来提供正则表达式来检查
@protocol RegularExpressionDelegate <NSObject>
-(NSArray<NSRegularExpression*>*)getRegularExpressions;
@end
/**
* `JSQMessagesCellTextView` is a subclass of `UITextView` that is used to display text
* in a `JSQMessagesCollectionViewCell`.
*/
@interface JSQMessagesCellTextView : UITextView
@property (weak) id<RegularExpressionDelegate> regularExpressionsDelegate;
@end
然后你需要把你的 viewController 作为 UITextViewDelegate 最后在你的 cellForRowAtIndexPath 你需要把这样的东西放
cell.textView.regularExpressionsDelegate = self;
cell.textView.delegate = self;
这会将你的viewController作为regularExpressionsDelegate,然后你需要实现这个方法,返回你希望被检测为海关链接的正则表达式
- (NSArray<NSRegularExpression*>*)getRegularExpressions
{
return [NSArray arrayWithObject:[NSRegularExpression regularExpressionWithPattern:@"#([a-zA-Z0-9])+" options:0 error:NULL]];
}
你也需要实现这个
//UITextViewDelegateMethod
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
{
//URL param will provide the link that was touched ej:#test
return YES;
}
希望对你有帮助,问候