1

セクション ヘッダーを持つ UITableView があります。テーブルビュー全体には、セルとヘッダーの両方に 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
    }


}

問題は、いくつかのセクション ヘッダーを非表示にしたいことです。ビューの代わりに nil を返すため、2 番目のセクション ヘッダーは非表示にする必要がありますが、スペースはまだ予約されています。なんで?

空のセクション ヘッダー用にスペースが予約されている UITableView のスクリーンショット

Github の Xcode プロジェクト: https://github.com/bvankuik/SectionHeaderAlwaysVisible

4

1 に答える 1

6

Apple のドキュメントにUITableViewAutomaticDimensionは次のように書かれています。

tableView:heightForHeaderInSection: または tableView:heightForFooterInSection: からこの値を返すと、タイトルが nil でない場合、 tableView:titleForHeaderInSection: または tableView:titleForFooterInSection: から返される値に適合する高さになります。

ヘッダーの高さを計算する方法を次のように変更する必要があると思います。

func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    if section == 1 {
        return 0
    } else {
        return UITableViewAutomaticDimension
    }
}
于 2016-04-11T09:47:01.583 に答える