首页 文章

使用UITableViewAutomaticDimension无法在UITableView中隐藏节 Headers

提问于
浏览
1

我有一个UITableView与节 Headers . 对于单元格和 Headers ,整个tableview都设置了UITableViewAutomaticDimension:

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet var sectionHeader: MyTableViewHeaderFooterView!

    let data = [
        "Lorem ipsum dolor sit amet",
        "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation",
        "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
    ]

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 44.0

        self.tableView.sectionHeaderHeight = UITableViewAutomaticDimension
        self.tableView.estimatedSectionHeaderHeight = 44.0
    }

    // MARK: - Table View

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }

    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 0 {
            self.sectionHeader.label.text = "Section \(section)"
            return self.sectionHeader
        } else {
            return nil
        }
    }

    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return UITableViewAutomaticDimension
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! MyTableViewCell
        cell.label.text = data[indexPath.row]
        return cell
    }


}

问题是我想隐藏一些节 Headers . 应该隐藏第二个节头,因为我返回nil而不是视图,但是仍然保留空间 . 为什么?

Screenshot of UITableView where space is reserved for an empty section header

Github上的Xcode项目:https://github.com/bvankuik/SectionHeaderAlwaysVisible

1 回答

  • 6

    Apple关于 UITableViewAutomaticDimension 的文档说:

    从tableView返回此值:heightForHeaderInSection:或tableView:heightForFooterInSection:得到一个高度,该高度适合从tableView返回的值:titleForHeaderInSection:或tableView:titleForFooterInSection:如果 Headers 不是nil .

    我担心你需要改变计算 Headers 高度的方式,如下所示:

    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 1 {
            return 0
        } else {
            return UITableViewAutomaticDimension
        }
    }
    

相关问题