ios 仿微信,短信聊天气泡

苹果短信的聊天气泡和微信的聊天气泡一直很经典,很小的一个气泡根据文字的多少适当变大变小。

ios 仿微信,短信聊天气泡_第1张图片

其实实现很简单,主要是控件的自适应撑高,这里用到的是cell。

核心代码

- (UIView*)bubbleView:(NSString *)textimageName:(NSString *)name

{

UIView *returnView= [[UIViewalloc] initWithFrame:CGRectZero];

UIImage*bubble;

returnView.backgroundColor= [UIColorclearColor];//ImageBubble@2x~iphone

if([name isEqualToString:@"1"]){//bubble-default-outgoing@2x

bubble= [[UIImageimageWithContentsOfFile:[[NSBundlemainBundle] pathForResource:@"bubble-default-incoming-green@2x"ofType:@"png"]]resizableImageWithCapInsets:UIEdgeInsetsMake(15.0f,25.0f,16.0f,23.0f)];

}else{

bubble= [[UIImageimageNamed:@"ImageBubble~iphone"]stretchableImageWithLeftCapWidth:15topCapHeight:14];

}

UIImageView *bubbleImageView= [[UIImageViewalloc] initWithImage:bubble];

UIFont *font= [UIFontsystemFontOfSize:13];

CGSize size= [textsizeWithFont:font constrainedToSize:CGSizeMake(220.0f,1000.0f)lineBreakMode: NSLineBreakByWordWrapping];

CGSize new1= [textsizeWithFont:font constrainedToSize:CGSizeMake(220.0f,size.height)lineBreakMode: NSLineBreakByWordWrapping];

UILabel*bubbleText;

if([name isEqualToString:@"1"]){

bubbleText = [[UILabel alloc] initWithFrame:CGRectMake(12.0f,5.0f,new1.width+10,new1.height+10)];

}else{

bubbleText = [[UILabel alloc] initWithFrame:CGRectMake(5.0f,5.0f,new1.width+10,new1.height+10)];

}

bubbleText.backgroundColor= [UIColorclearColor];

bubbleText.font= font;

bubbleText.numberOfLines= 0;

bubbleText.lineBreakMode= NSLineBreakByWordWrapping;

bubbleText.text= text;

bubbleImageView.frame= CGRectMake(0.0f,0.0f,new1.width+ 20, new1.height+20.0f);

if([name isEqualToString:@"1"]){

returnView.frame= CGRectMake(40.0f,30.0f,new1.width+ 20, new1.height+20.0f);

}else{

returnView.frame= CGRectMake(260.0f- new1.width,40.0f,new1.width+ 20, new1.height+20.0f);

}

[returnView addSubview:bubbleImageView];

[returnView addSubview:bubbleText];

returnreturnView ;

这段代码可以直接使用,在tableview的代理方法里还要实现cell自适应的高度

- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath

最后着重提出一点,其实网上很多类似的demo都可以实现此类效果,但有的demo拿过来发现气泡吹变形了,这可不是方法出了问题,是图片的问题,多找些气泡试试。lz就是被这个事情困扰了好久,换了好几个版本的方法发现

你可能感兴趣的:(ios 仿微信,短信聊天气泡)