您的位置:首页 > 移动开发 > IOS开发

仿QQ聊天布局--iOS

2014-06-24 12:06 183 查看
  虽然注册博客园这么久了,但很少在这上面写些东西,一来也是觉得自己能力不够,二来怕误人子弟,所以一直秉着“多看,多做,少说”的原则混迹在各论坛之中。但日子久了,觉着这其实是一种逃避的方法。思来想去,那些牛逼的人其实是那些能把自己心中所想完全表达出来,让人看之舒服,听之认同的人。所以,除了“多看,多做,少说”外,怕要加一条“多总结”,否则恐要淹死在这信息化的浪潮中了。

  最近对QQ、微信聊天布局产生兴趣,便搜索资料试着搞搞,趁着空隙,先上效果图,得空再补充说明。



  大致思路就是 自定义tableViewcell(包括imageView和UIButton),选用button是因为他既可以设置背景也可以显示文字,如果用Label只能显示文字。

  下面是大致的框架:

  


  

  要解决的难点就是怎样实现让cell高度随着文本的大小显示,iOS7 摒弃了原来的sizeWithFont: constrainedToSize:lineBreakMode:方法,采用了boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(NSDictionary *)attributes context:(NSStringDrawingContext *)context的方法,以及设置button的UIEdgeInsetsMake(CGFloat top, CGFloat left, CGFloat bottom, CGFloat right)使文字在中间显示,当然还得解决背景图片的拉伸问题,关于拉伸的解决方法提供一个网址写得不错:/article/4834658.html

添上本工程代码:

// 按钮的文本
NSDictionary *attributes = @{NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:kUIFontSize]};
CGSize maximumLabelSize = CGSizeMake(180, MAXFLOAT);
CGRect size = [message.message boundingRectWithSize:maximumLabelSize options:(NSStringDrawingUsesLineFragmentOrigin) attributes:attributes context:nil];
// 2) 设置文字按钮的文本
NSLog(@"%@ %@", NSStringFromCGSize(size.size), message.message);

// 3) 设置文字按钮的大小和位置
CGFloat x = 0;
if (message.fromSelf) {
x = 250 - 10 - size.size.width - 40;
//        NSLog(@"x = %f",x);
} else {
x = 80;
}
// 增加消息按钮的外间距
[self.massage setContentEdgeInsets:UIEdgeInsetsMake(5, 20,10, 20)];

self.massage.frame = CGRectMake(x, 10, size.size.width + 20, size.size.height + 20);
[self.massage setTitle:message.message forState:UIControlStateNormal];

// 按钮的背景
UIImage *nomalImg;
UIImage *highImg;
if(message.fromSelf)
{
nomalImg = [UIImage imageNamed:@"chatto_bg_normal"];
highImg = [UIImage imageNamed:@"chatto_bg_focused"];

}else
{
nomalImg = [UIImage imageNamed:@"chatfrom_bg_normal"];
highImg = [UIImage imageNamed:@"chatfrom_bg_focused"];

}

// 拉伸图像
nomalImg = [nomalImg stretchableImageWithLeftCapWidth:nomalImg.size.width * 0.5 topCapHeight:nomalImg.size.height *0.6];
highImg = [highImg stretchableImageWithLeftCapWidth:highImg.size.width * 0.5 topCapHeight:highImg.size.height *0.6];

[self.massage setBackgroundImage:nomalImg forState:UIControlStateNormal
];
[self.massage setBackgroundImage:highImg forState:UIControlStateHighlighted];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐