我正在使用快速的framework,并且需要在消息文本字符串中包含#标记。如果用户发送包含以#开头的代码的消息,例如:#t3Us9K,则单个“单词”必须是所有用户都可以按下的链接。请告诉我这是否可行,以及如何做到这一点。

最佳答案

我一直在研究您的问题,这是我的结果,

首先,您需要修改库中的JSQMessagesCellTextView并添加一种方法来帮助您检测自定义链接,例如#test。如果您希望添加此功能来克隆我的fork,这就是它的外观,那么动画问题就是因为我的gif转换器

ios - JSQMessagesViewController自定义链接-LMLPHP

已编辑

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

希望这对您有帮助

关于ios - JSQMessagesViewController自定义链接,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38132110/

10-11 22:40
查看更多