Ios 在TableView中显示标题
我开始为一件我不能做的简单事情而疯狂:显示tabeview标题。我正在使用带有动态表视图的Swift 3.0。在这个tableview中,我创建了一个联系人目录,用户可以在其中添加联系人列表。 我使用动态原型内容在故事板中声明我的tableview。以编程方式,我做了我需要做的事情,以使我的联系人列表和列表在我的表视图中正确显示 然后,我使用以下方法声明1节和:Ios 在TableView中显示标题,ios,header,swift3,tableview,Ios,Header,Swift3,Tableview,我开始为一件我不能做的简单事情而疯狂:显示tabeview标题。我正在使用带有动态表视图的Swift 3.0。在这个tableview中,我创建了一个联系人目录,用户可以在其中添加联系人列表。 我使用动态原型内容在故事板中声明我的tableview。以编程方式,我做了我需要做的事情,以使我的联系人列表和列表在我的表视图中正确显示 然后,我使用以下方法声明1节和: override func numberOfSections(in tableView: UITableView) -> Int
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: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
}
=>结果是没有标题,只显示我的列表。有什么建议可以显示标题吗?您需要稍微修改
headerinsection
的高度和查看headerinsection
的方法。
您必须为这两种方法添加一个覆盖,并在第一个括号后为这两种方法添加一个“\u1”。(见下文)
使用此代码,将为我显示节标题
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
}