我在我的故事板上使用了一个静态Tableview,它具有指向各个部分的标题
标题文本的颜色和大小是一个静态的东西,我不能改变它,它会导致非常窄的标题和黑色文本。
如何分隔标题(使高度稍大一点)并更改文本的颜色?
发布于 2018-12-04 17:29:37
如何分隔标题(使高度稍大一点)并更改文本的颜色?
您需要有一个具有标签的自定义视图,并将其返回给UITableView
的viewForHeaderInSection
的委托方法。
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
参考文献:
编辑:
下面是如何实现这一点。基本上,在我上面提到的委托方法中,您需要一个自定义视图。如果您以前已经在cellForRow
中成功地创建了一个自定义UITableViewCell
,那么这对您来说应该是小菜一碟。
声明一个容器视图,然后在该容器中添加子视图,在本例中是一个UILabel
。我总是使用约束,如下所示:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
// Let's make the even numbers sections a red background.
// Blue background for odd numbers
let container = UIView()
container.backgroundColor = section % 2 == 0 ? .red : .blue
let titleForHeaderLabel = UILabel()
titleForHeaderLabel.backgroundColor = .white
titleForHeaderLabel.text = "HEADER SECTION: \(section)"
container.addSubview(titleForHeaderLabel)
titleForHeaderLabel.translatesAutoresizingMaskIntoConstraints = false
titleForHeaderLabel.topAnchor.constraint(equalTo: container.topAnchor, constant: 20).isActive = true
titleForHeaderLabel.bottomAnchor.constraint(equalTo: container.bottomAnchor, constant: -20.0).isActive = true
titleForHeaderLabel.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: 20.0).isActive = true
titleForHeaderLabel.trailingAnchor.constraint(equalTo: container.trailingAnchor, constant: -20.0).isActive = true
return container
}
然后在func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat
委托方法中为截面提供高度,如下所示:
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 80.0
}
输出:
很简单,对吧?:)我希望这对你有帮助!
https://stackoverflow.com/questions/53609372
复制相似问题