美文网首页iOS应用开发
tableViewCell高度&tableView高度

tableViewCell高度&tableView高度

作者: d60e80cd17d5 | 来源:发表于2017-05-15 11:13 被阅读0次

    在iOS日常开发中,tableview是一个经常用的控件,今天我们就来聊聊tableView的高度和tableViewCell的高度的不同组合情况。

    开始之前定义一些常用参数:固定cell高度(fixedCellHeight),cell总数(cellCount),tableView最大高度限制(maxTableViewHeight),默认tableView的最大显示范围为view.bounds

    tableViewCell固定高度

    tableView.rowHeight = fixedCellHeight

    或者(二选一,也可以都写)

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    return fixedCellHeight

    }

    tableView的高度与cell无关

    这种是我们经常遇到的情况,像一些设置界面,显示本地消息界面,都是这种情况。

    tableView.frame = view.bounds

    tableView的高度与cell有关

    这种情况,产生的情景通常为上拉,下滑,弹出框出现的一些选项。

    我这里就先写一下下滑

    let cellTotalHeight =fixedCellHeight *cellCount

    tableView.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: cellTotalHeight > maxTableViewHeight ? maxTableViewHeight : cellTotalHeight)

    tableView.isScrollEnabled = (cellTotalHeight > maxTableViewHeight)

    这个需要考虑所有cell高度和有没有超过tableView的最大高度限制,因为不能让tableView的frame超过了屏幕,或者其所在的框框里。如果cell高度和超过了最大高度限制,那么tableView高度就取最大高度限制,tableView可滑动,反之就取cell高度和,tableView不可滑动。

    tableViewCell自适应高度

    在viewDidLoad写下如下代码

    tableView.estimatedRowHeight = 60//预估最接近的高度平均值

    tableView.rowHeight = UITableViewAutomaticDimension

    tableView的高度与cell无关

    代码跟tableViewCell固定高度时一样

    tableView.frame = view.bounds

    tableView的高度与cell有关

    这种情况也是经常出现在上拉,下滑,弹出框选项,只是每个选项的高度由内容确定。这就是全文最大的难点处了。同样是比较tableView的最大高度限制和cell的高度和,但是在cell显示之前,我们都不能确定每个cell到底有多高,也不知道cell高度和到底是多少。

    其实,在tableView显示最后一个cell的时候,tableView.contentSize.height,就是所有tableViewCell高度和。那么,我们只需要在将要显示最后一个cell的时候,作出判断就行了。

    先在viewDidLoad中设置默认情况:tableView高度为最大高度限制,tableView可滑动,这种设置是针对cell高度和大于tableView最大高度限制。

    tableView.frame = view.bounds

    tableView.isScrollEnabled = true

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

    if ( indexPath.row == (self.dataSource.count - 1) && self.itemsTable.contentSize.height <= maxTableViewHeight){

    layoutTable(with: maxTableViewHeight)

    tableView.isScrollEnabled

    }}

    if 语句中首先判断是否是最后一行,如果是最后一行,判断所有cell的高度和是否小于tableView的最大高度限制,如果是的话,重新设置tableView的高度为tableView的最大高度限制,tableView不可滑动。

    总结

    tableView的高度和tableView的高度设置是分开的,前三种情况都非常常见简单,最后一种情况稍微复杂点。对于最后一种情况,这只是一种实现方式,如果有更好的实现方式,👏欢迎提出。

    ps: 只是用代码简单的写了下思想,具体实现当然要考虑具体情况,做相应的修改。例如:设置tableView的高度可以用约束😄

    相关文章

      网友评论

        本文标题:tableViewCell高度&tableView高度

        本文链接:https://www.haomeiwen.com/subject/kylgtxtx.html