iOS之如何自适应TableViewCell的高度

来源:互联网 发布:php true false 编辑:程序博客网 时间:2024/05/21 05:39

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!    }

3.详见代码部分(ViewController+TableView.swift)

源码:我的Github

1 1
原创粉丝点击