我想分享一些我为解决这个问题而编写的代码,我在挖掘了很多答案并遇到了许多故障之后。这适用于 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 上)。
希望对您有所帮助,如果您有改进建议,请告诉我。