我在我的故事板上使用了一个静态Tableview,它是这些部分的头条新闻
标题文字颜色和大小是一个静态的东西,我不能改变它导致非常狭窄的标题和黑色文字.
如何区分标题(使高度更大)并更改文本的颜色?
我怎样才能将标题空间化(使高度更大)并改变文本的颜色?
您需要拥有一个带有标签的自定义视图,并将其返回给UITableViews 的委托方法viewForHeaderInSection.
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
Run Code Online (Sandbox Code Playgroud)
参考:
https://www.hackingwithswift.com/example-code/uikit/how-to-add-a-section-header-to-a-table-view
https://developer.apple.com/documentation/uikit/uitableview/1614965-headerview
编辑:
以下是如何实现这一目标.基本上,您需要在我上面提到的委托方法中使用自定义视图.如果你已经成功地UITableViewCell在cellForRow之前制作了一个定制,那么这个应该是你的小菜一碟.
您声明一个容器视图,然后在该容器中添加您的子视图,在您的情况下,a 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
}
Run Code Online (Sandbox Code Playgroud)
然后在func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat委托方法中为您的部分提供高度,如下所示:
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 80.0
}
Run Code Online (Sandbox Code Playgroud)
输出:
容易,对吗?:) 我希望这有帮助!
| 归档时间: |
|
| 查看次数: |
114 次 |
| 最近记录: |