JSQMessagesViewController自定义链接

我正在使用一个快速的框架 ,我需要能够在消息文本string中有一个像标签。 如果用户发送包含前缀为#的代码的消息,例如:#t3Us9K单个“单词”需要是所有用户可以按下的链接。 请告诉我,如果这是可能的,如果是的话如何做到这一点。

我一直在处理你的问题,这是我的结果,

首先,您需要修改JSQMessagesCellTextView中的JSQMessagesCellTextView ,并添加一个方法来帮助您检测自定义链接,例如#test。如果您希望您可以克隆添加了此function的fork,并且这是它的外观,那么animation问题是因为我的GIF转换器

在这里输入图像说明

EDITED

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; } 

我已经添加了一个委托来提供正则expression式来检查

 @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然后你需要实现这个方法,返回你想检测的正则expression式作为海关链接

 - (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; } 

我希望这可以帮助你,关心