iOS之如何自适应TableViewCell的高度
来源:互联网 发布:室内设计软件培训班 编辑:程序博客网 时间:2024/05/21 01:53
1. 问题描述:
在项目中会遇到由于每个cell的图片和文本大小不一致,如果cell的height高度设置不合理的话,对用户体验不是很好。但是如果对cell的height高度设定死之后,当遇到大量文本的话也会出现问题。所以这就需要在每次对cell进行绘制的时候对cell的height进行计算,然后再绘制cell。但是一般情况下,这种对cell的height计算会比较复杂。但是Apple自iOS 8之后推出了一种新的方式,可以用几行代码就可以设置cell的自适应高度,连func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { }方法都可以进行省略。
解决方案:
//iOS 8开始的自适应高度,可以不需要实现定义高度的方法 self.tableView.estimatedRowHeight = 200 self.tableView.rowHeight = UITableViewAutomaticDimensio添加如上代码之后,然后运行之后,就可以发现一个惊奇的效果~
2. 问题描述:
在按照1中解决方案修改代码之后,重新运行项目,发现cell的图片有些压缩,并没有出现自适应高度的效果。但是当你用鼠标往下拉动cell的之后,令人奇怪的一幕发生了,这个时候所有的cell都变大也就是cell的自适应高度有效果了。那究竟原因是什么呢?
解决方案:
在review代码几分钟之后,发现了原因。因为我在对cell中的图片进行赋值的时候,是采用的异步加载图片,所以计算图片的高度会需要一会时间,以至于我往后拉一下所有的图片就会恢复到自身的大小。于是,我在对cell的图片控件进行赋值的时候,是采用直接赋值,也就是同步操作。详见代码:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let initIdentifier = "MyCell" var cell = tableView.dequeueReusableCellWithIdentifier(initIdentifier) as? NewsTableViewCell if cell == nil{ tableView.registerNib(UINib(nibName: "NewsTableViewCell", bundle: nil), forCellReuseIdentifier: initIdentifier) cell = tableView.dequeueReusableCellWithIdentifier(initIdentifier) as? NewsTableViewCell } //进行cell的绘制 let model = self.items1[indexPath.row]// cell?.headerImage.image = UIImage(data: NSData(contentsOfURL: NSURL(string: model.newsImageName)!)!) //利用SDWebImage异步加载图片 cell?.headerImage.sd_setImageWithURL(NSURL(string: model.newsImageName)) //图片圆角功能// cell?.headerImage.layer.cornerRadius = 60// cell?.headerImage.layer.masksToBounds = true cell?.headerLabel.text = model.newsTitle cell?.selectionStyle = UITableViewCellSelectionStyle.None return cell! }
1 0
- iOS之如何自适应TableViewCell的高度
- iOS之如何自适应TableViewCell的高度
- [iOS] TableViewCell 自适应高度
- iOS开发之tableViewCell高度自适应
- 自适应tableViewCell的高度
- TableViewCell高度的自适应
- iOS tableviewcell 高度自适应方法
- IOS-根据TableviewCell 总体高度 做自适应
- IOS TableViewCell嵌套webview 自适应高度
- iOS UI设计: 在Autolayout自适应的情况下tableviewcell高度自适应
- tableViewCell根据内容自适应高度的方法
- TableViewCell高度自适应的实现方案
- tableViewCell 自适应高度
- tableViewcell高度自适应
- tableViewcell高度自适应
- TableViewCell自适应高度
- tableViewCell自适应高度
- TableviewCell高度自适应
- a
- Android关于手机适配的一些问题
- Apache Calcite:Hadoop中新型大数据查询引擎
- SBT安装与编译运行
- CLGeocoder 根据地理位置获取经纬度,根据经纬度获取地理位置
- iOS之如何自适应TableViewCell的高度
- Git bad permissions
- PHP 读取文件的三个方法fgets ,fgetcsv, fgetss
- 插入省市
- Serlvet 处理http请求并保持长连接
- java基础知识:继承
- It looks like git-am is in progress. Cannot rebase.
- 个人学习-java-set的实现
- MapKit显示用户的位置