【问题标题】:Display Header in TableView在 TableView 中显示标题
【发布时间】:2017-01-15 18:44:44
【问题描述】:

我开始为一件我不能做的简单事情而疯狂:显示 tabeview Header 。我正在使用带有动态表视图的 Swift 3.0。在这个表格视图中,我正在创建一个联系人目录,用户可以在其中添加联系人列表。 我在情节提要中使用动态原型内容声明了我的 tableview。我以编程方式做我需要做的事情来获得我的联系人列表,并且我的列表在我的表格视图中正确显示。

然后我声明 1 部分并使用以下方法:

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

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

            return 50.0
}

在标题中,我添加了一个按钮来对我的联系人列表执行一些操作:

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

    let frame: CGRect = tableView.frame
    let DoneBut: UIButton = UIButton(frame: CGRect(x: frame.size.width - 200, y: 0, width: 150, height: 50))
    DoneBut.setTitle("Done", for: .normal)
    DoneBut.backgroundColor = UIColor.red



    DoneBut.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)

    DoneBut.backgroundColor = UIColor.blue


    let headerView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height))
    headerView.backgroundColor = UIColor.red
    headerView.addSubview(DoneBut)

    return headerView


}

=> 结果是没有 Header 只显示我的列表。有什么建议可以到 Header 吗?

【问题讨论】:

    标签: ios header swift3 tableview


    【解决方案1】:

    您需要稍微修改您的 heightForHeaderInSectionviewForHeaderInSection 方法。 您必须在这两种方法的第一个括号后添加一个覆盖和一个“_”。 (见下文)

    使用此代码,部分标题会显示给我。

    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
            return 50.0
        }
    
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let frame: CGRect = tableView.frame
        let DoneBut: UIButton = UIButton(frame: CGRect(x: frame.size.width - 200, y: 0, width: 150, height: 50))
        DoneBut.setTitle("Done", for: .normal)
        DoneBut.backgroundColor = UIColor.red
    
    
    
        DoneBut.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
    
        DoneBut.backgroundColor = UIColor.blue
    
    
        let headerView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: 50))
        headerView.backgroundColor = UIColor.red
        headerView.addSubview(DoneBut)
    
        return headerView
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-22
      • 1970-01-01
      相关资源
      最近更新 更多