美文网首页IMiOS 开发 iOS软件开发
iOS环信聊天界面,URL处理

iOS环信聊天界面,URL处理

作者: 船长_ | 来源:发表于2016-04-19 22:14 被阅读3017次

环信聊天界面,如果是超链接,目前版本是不支持打开的,之前是有版本支持的,这个属于UI层,需要我们自己处理;

思路

  • 1.检测聊天文本,如果是超链接,添加下划线-->UILabel富文本属性
  • 2.监听文本点击事件,如果是超链接打开-->chatViewController代理方法

具体代码

1.EaseMessageCell添加分类,在分类里判断是否是超链接,是超链接加下划线

@implementation EaseMessageCell (DXLinkClick)

-(void)addLinks:(NSString*)str toLabel:(UILabel*)label
{
    NSMutableAttributedString*strMutable=[[NSMutableAttributedString alloc]initWithString:str];
    [strMutable addAttribute:NSFontAttributeName value:label.font range:NSMakeRange(0, str.length)];
    [strMutable addAttribute:NSForegroundColorAttributeName value:label.textColor range:NSMakeRange(0, str.length)];
    NSDataDetector*detect=[[NSDataDetector alloc]    initWithTypes:NSTextCheckingTypeLink error:nil];

    NSArray*matches=[detect matchesInString:str options:0 range:NSMakeRange(0, str.length)];

    for(NSTextCheckingResult*result in matches)
    {
        if (result.resultType==NSTextCheckingTypeLink) {
            [strMutable addAttribute:NSLinkAttributeName value:@"http://www.baidu.com" range:result.range ];
        }
    }
    if ([matches count]>0) {
        label.attributedText=strMutable;
    }
}
@end

2.在自定义的EaseMessageCell里,在模型的set方法里调用分类方法

- (void)setModel:(id<IMessageModel>)model
{
    _model = model;
    if ([self respondsToSelector:@selector(isCustomBubbleView:)] && [self isCustomBubbleView:model]) {
        [self setCustomModel:model];
    } else {
        switch (model.bodyType) {
            case eMessageBodyType_Text:
            {
                _bubbleView.textLabel.text = model.text;
                [self addLinks:model.text toLabel:_bubbleView.textLabel];

            }
                break;
   // 以下省略好多字

3.在chatViewController中,重写代理方法

- (BOOL)messageViewController:(EaseMessageViewController *)viewController didSelectMessageModel:(id<IMessageModel>)messageModel
{
    BOOL flag = NO;
    NSString*str=[messageModel text];
    NSDataDetector*detector=[[NSDataDetector alloc]initWithTypes:NSTextCheckingTypeLink error:nil];
    NSArray*array=[detector matchesInString:str options:0 range:NSMakeRange(0, str.length)];
    if([array count]>0)
       {
        // 这里用Safari打开了,也可以自定义在app内打开
          [[UIApplication sharedApplication] openURL:[NSURL URLWithString:resultStr]];
       }
    return flag;
}

相关文章

网友评论

  • mayday2024:感谢博主 让我找到了方法
    mayday2024:多个链接的话我就弹出让用户自己选择
  • 6a53b918bd3c:这样处理真的不好
  • 飛呈Geek:> [[UIApplication sharedApplication] openURL:[NSURL URLWithString:resultStr]];
    resultStr哪里来的。。。
    如果text里面有多个链接呢?如果我点击的不是链接呢。。这样处理不太好。
    yzhi00:@飛呈Geek 你好,你借助TTTAttributedLabel来处理的时候,是怎么计算TTTAttributedLabel的高度的?我发现怎么计算不了正确的高度,可以告知一下吗?谢谢!
    飛呈Geek:@2c4329d34627 我是借助了TTTAttributedLabel来处理的,不知道有没有更好的办法。
    http://www.jianshu.com/p/c0e50ba84512
    努力才幸运:@飛呈Geek 那怎么处理呢

本文标题:iOS环信聊天界面,URL处理

本文链接:https://www.haomeiwen.com/subject/agdzlttx.html