【问题标题】:How to show and hide Custom UITableView Header Cell of Table View in Swift3 iOS如何在 Swift3 iOS 中显示和隐藏表格视图的自定义 UITableView 标题单元格
【发布时间】:2018-11-01 05:00:59
【问题描述】:

我正在 Swift3 中开发一个应用程序,我必须为不同的用户显示和隐藏 UITableView Header。为了显示UITableView Header View,我创建了UITableViewCell 的自定义类CustomHeaderCell

这是我的代码:

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

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        let headerCell = tableView.dequeueReusableCell(withIdentifier: "HeaderCell") as! CustomHeaderCell

        return headerCell
    }

现在谁能帮我隐藏我UITableView 的这个标题?

注意:我尝试使用此 tableView.tableHeaderView?.isHidden = true,但无法正常工作。我是否需要在heightForHeaderInSection 中进行验证?

添加HeaderViewCell的参考链接:http://www.accella.net/knowledgebase/custom-header-and-footer-views-for-uitableviews/

【问题讨论】:

    标签: ios uitableview swift3 header


    【解决方案1】:

    如果您有办法区分用户,那么您可以像这样更改标题高度

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if userA {
            return 235.0
        } else {
            return 0
        }
    }
    

    这应该有助于隐藏标题

    【讨论】:

    • 我知道@Prasad,还有其他方法吗?
    • @user2786 我不这么认为。我们可以尝试在 viewForHeaderInSection 中返回 nil,但这会导致异常。由于我们只想隐藏它而不是删除它,因此将其高度设置为 0 将是最直接的解决方案。
    【解决方案2】:

    您正在混合tableHeaderView 和节标题视图,它们是不同的:

    • tableHeaderView 是一个视图,显示为整个 UITableView 的标题
    • 节标题视图是可重复使用的视图,用于在每个节上方显示标题

    在您的情况下,您想使用部分标题视图,因此您应该为不关心的用户返回空视图(我假设这里 sectionNeedHeader 将被您的条件替换)。

    另外,您最好使用UITableViewHeaderFooterView 而不是UITableViewCell。该行为在全局范围内是相同的,但它是为此用途而设计的:

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if sectionNeedHeader {
            return 235.0
        }
    
        return 0.0
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if sectionNeedHeader {
            let headerCell = tableView.dequeueReusableHeaderFooterView(withIdentifier: "HeaderView") as! CustomHeaderView
            return headerView
        }
    
        return nil
    }
    

    【讨论】:

    • 感谢@Thomas 的建议,我有多个验证。这是实现这一目标的唯一方法还是也可以通过代码实现?
    • 为避免出现多个条件,可以在 heightForHeaderInSection 函数中返回 UITableViewAutomaticDimension,并使用自动布局来设置您的标题视图布局(在这种情况下,标题视图高度将由约束设置)。更多关于 UITableViewAutomaticDimension 的信息在这里:developer.apple.com/library/content/documentation/…
    猜你喜欢
    • 2020-02-29
    • 1970-01-01
    • 2015-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多