首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在tableview xcode中调整标题大小和更改标题颜色

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

Stack Overflow用户
提问于 2018-12-04 17:16:16
回答 1查看 132关注 0票数 4

我在我的故事板上使用了一个静态Tableview,它具有指向各个部分的标题

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-04 17:29:37

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

您需要有一个具有标签的自定义视图,并将其返回给UITableViewviewForHeaderInSection的委托方法。

代码语言:javascript
复制
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?

参考文献:

  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

编辑:

下面是如何实现这一点。基本上,在我上面提到的委托方法中,您需要一个自定义视图。如果您以前已经在cellForRow中成功地创建了一个自定义UITableViewCell,那么这对您来说应该是小菜一碟。

声明一个容器视图,然后在该容器中添加子视图,在本例中是一个UILabel。我总是使用约束,如下所示:

代码语言:javascript
复制
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委托方法中为截面提供高度,如下所示:

代码语言:javascript
复制
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 80.0
}

输出:

很简单,对吧?:)我希望这对你有帮助!

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53609372

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档