如何在tableview xcode中调整大小和更改标题的颜色

Chi*_*dog 4 ios swift

我在我的故事板上使用了一个静态Tableview,它是这些部分的头条新闻

在此输入图像描述

标题文字颜色和大小是一个静态的东西,我不能改变它导致非常狭窄的标题和黑色文字.

如何区分标题(使高度更大)并更改文本的颜色?

在此输入图像描述

Gle*_*enn 5

我怎样才能将标题空间化(使高度更大)并改变文本的颜色?

您需要拥有一个带有标签的自定义视图,并将其返回给UITableViews 的委托方法viewForHeaderInSection.

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
Run Code Online (Sandbox Code Playgroud)

参考:

  1. https://www.hackingwithswift.com/example-code/uikit/how-to-add-a-section-header-to-a-table-view

  2. https://developer.apple.com/documentation/uikit/uitableview/1614965-headerview

编辑:

以下是如何实现这一目标.基本上,您需要在我上面提到的委托方法中使用自定义视图.如果你已经成功地UITableViewCellcellForRow之前制作了一个定制,那么这个应该是你的小菜一碟.

您声明一个容器视图,然后在该容器中添加您的子视图,在您的情况下,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)

输出:

在此输入图像描述

容易,对吗?:) 我希望这有帮助!