苹果短信的聊天气泡和微信的聊天气泡一直很经典,很小的一个气泡根据文字的多少适当变大变小。
其实实现很简单,主要是控件的自适应撑高,这里用到的是cell。
核心代码
- (UIView*)bubbleView:(NSString*)textimageName:(NSString*)name
{
UIView *returnView=[[UIViewalloc]initWithFrame:CGRectZero];
UIImage*bubble;
returnView.backgroundColor=[UIColorclearColor];//ImageBubble@2x~iphone
if([nameisEqualToString:@"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:fontconstrainedToSize:CGSizeMake(220.0f,1000.0f)lineBreakMode: NSLineBreakByWordWrapping];
CGSize new1=[textsizeWithFont:fontconstrainedToSize:CGSizeMake(220.0f,size.height)lineBreakMode: NSLineBreakByWordWrapping];
UILabel*bubbleText;
if([nameisEqualToString:@"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([nameisEqualToString:@"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*)tableViewheightForRowAtIndexPath:(NSIndexPath*)indexPath