ios 仿微信,短信聊天气泡

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


其实实现很简单,主要是控件的自适应撑高,这里用到的是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就是被这个事情困扰了好久,换了好几个版本的方法发现

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值