天天看点

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

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

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

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

核心代码

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

{

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

    UIImage*bubble;

returnView.backgroundColor=[UIColorclearColor];//[email protected]~iphone

    if([nameisEqualToString:@"1"]){//[email protected]

        bubble=[[UIImageimageWithContentsOfFile:[[NSBundlemainBundle]pathForResource:@"[email protected]"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

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