iOS App开发中使cell高度自适应的黑魔法详解
在使用tableview的时侯经常会遇到这样的需求:tableview的cell中的内容是动态的,导致在开发的时候不知道一个cell的高度具体是多少,所以需要提供一个计算cell高度的算法,在每次加载到这个cell的时候计算出cell真正的高度。
在iOS8之前
没有使用Autolayout的情况下,需要实现tableviewdelegate的tableView(tableView:UITableView,heightForRowAtIndexPathindexPath:NSIndexPath)->CGFloat方法,在这个方法中计算并返回cell的高度。比如,我有一个可以显示任意行数的纯文本cell,计算cell的代码可以是这样:
overridefunctableView(tableView:UITableView,heightForRowAtIndexPathindexPath:NSIndexPath)->CGFloat{
letcontent=self.datas[indexPath.row]asString
letpadding:CGFloat=20 letwidth=tableView.frame.size.width-padding*2;
letsize=CGSizeMake(width,CGFloat.max) letattributes=[NSFontAttributeName:UIFont(name:"Helvetica",size:14)!] letframe=content.boundingRectWithSize(size, options:NSStringDrawingOptions.UsesLineFragmentOrigin, attributes:attributes, context:nil) returnframe.size.height+1; }
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下