iOS环信聊天界面,URL处理
2016-04-19 本文已影响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;
}