蘋果短信的聊天氣泡和微信的聊天氣泡一直很經典,很小的一個氣泡根據文字的多少適當變大變小。
其實實現很簡單,主要是控件的自適應撐高,這裡用到的是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