多くの回答を掘り下げ、多くの不具合にぶつかった後、この問題を解決するために書いたコードを共有したいと思いました。これは xCode 7.2.1 用です。(Swift でのコード例)
私の使用例は、ストーリーボードの静的グループ化された TableView の使いやすさを使用したいというものでしたが、ユーザー プロファイルに基づいて特定のセクションを非表示にする必要がありました。これを機能させるには (他の投稿で説明されているように)、ヘッダーとフッター、セクションの行を非表示にし、ヘッダー/フッターのテキストを非表示にする必要があります (少なくとも上部のセクションで)。テキストを非表示 (透明にする) にしないと、ユーザーはテーブルの上部 (ナビゲーション コントローラーの下) を超えて上にスクロールし、テキストがすべてぎっしり詰まっているのを見ることができることがわかりました。
これを簡単に変更できるようにし、コード全体に条件が広がらないようにしたかったので、shouldHideSection(section: Int) という単一の関数を作成しました。これは、非表示にする行を変更するために変更する必要がある唯一の関数です。
func shouldHideSection(section: Int) -> Bool {
switch section {
case 0: // Hide this section based on condition below
return user!.isProvider() ? false : true
case 2:
return someLogicForHiddingSectionThree() ? false : true
default:
return false
}
}
コードの残りの部分は、shouldHideSection() を呼び出すだけです。
// Hide Header(s)
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return shouldHideSection(section) ? 0.1 : super.tableView(tableView, heightForHeaderInSection: section)
}
// Hide footer(s)
override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return shouldHideSection(section) ? 0.1 : super.tableView(tableView, heightForFooterInSection: section)
}
// Hide rows in hidden sections
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return shouldHideSection(indexPath.section) ? 0 : super.tableView(tableView, heightForRowAtIndexPath: indexPath)
}
// Hide header text by making clear
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if shouldHideSection(section) {
let headerView = view as! UITableViewHeaderFooterView
headerView.textLabel!.textColor = UIColor.clearColor()
}
}
// Hide footer text by making clear
override func tableView(tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
if shouldHideSection(section) {
let footerView = view as! UITableViewHeaderFooterView
footerView.textLabel!.textColor = UIColor.clearColor()
}
}
多くの異なる値 (0、0.1、-1、... を返す) を試して、最終的に満足のいく解決策を得る必要がありました (少なくとも iOS 9.x では)。
これが役立つことを願っています。改善を提案した場合はお知らせください。