我正在使用 Xib 文件而不是情节提要。我创建了一个包含一些虚拟数据的表格视图。它工作正常,现在我创建了一个带有一些标签和文本字段的自定义单元格。如何将它用作 UITableView 的页眉或页脚?
问问题
16237 次
3 回答
33
答案其实很简单。viewForHeaderInSection()
像您一样创建单元格对象cellForRowAtIndexPath()
并返回它。
这是示例代码。
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let cell = tableView.dequeueReusableCellWithIdentifier("cellIdentifier") as! YourTableViewCell
return cell
}
您可以将标题的高度设置为:
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 80
}
Swift 4.2 更新
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier") as! YourTableViewCell
return cell
}
和
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 80
}
于 2016-09-26T10:26:13.767 回答
2
您可以以编程方式创建自定义视图。我尝试了以下代码。试一次。
override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let customview:UIView = UIView();
let label = UILabel();
label.text = "ur custom data"
/*
You can add any number of subviews you want here
And don't forget to add it to your customview.
*/
customview.addSubview(label)
return customview;
}
同样,您也可以对标题做同样的事情。
于 2016-07-01T08:26:10.593 回答
2
这是添加 TableView 标题的方法:您可以在其中任何控件,如 UIButton、UIImageView、....等。
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let sectionView = UIView()
sectionView.frame = CGRectMake(x,y,height,width) // For Set the Frame
sectionView.backgroundColor = UIColor.redColor()
return sectionView
}
func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let sectionView = UIView()
sectionView.frame = CGRectMake(x,y,height,width) // For Set the Frame
sectionView.backgroundColor = UIColor.redColor()
return sectionView
}
像上面一样,您可以设置部分的页脚,您可以添加页眉和页脚的大小
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 20.0
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 20.0
}
斯威夫特 4.0
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let sectionView = UIView()
sectionView.frame = CGRect(x: x, y: y, width: width, height: height)// For Set the Frame
sectionView.backgroundColor = UIColor.red
return sectionView
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let sectionView = UIView()
sectionView.frame = CGRect(x: x, y: y, width: width, height: height)// For Set the Frame
sectionView.backgroundColor = UIColor.red
return sectionView
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 20.0
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 20.0
}
于 2016-07-01T09:19:53.053 回答