OGeek|极客世界-中国程序员成长平台

标题: ios - 在 UITableView 中使用动态标签宽度管理自动标题高度 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:49
标题: ios - 在 UITableView 中使用动态标签宽度管理自动标题高度

我想创建一个具有动态高度的 UITableView header 。我在 View 中有四个标签,并且必须根据每个 UILabel 中的内容调整标题的高度。我想实现与此图像类似的东西。 Sample image.

这里标签的宽度将根据屏幕大小动态变化。 “类型”标签将覆盖大约 2/3 的屏幕,其余部分将在三个标签之间平均分配。这里根据屏幕大小标签可能是多行的,我想根据标签的内容管理主视图的高度。

当我为标签提供固定宽度约束时,我能够成功地管理高度,但我想保持标签的宽度是动态的。这是一个 UITableView header 。任何帮助将不胜感激。



Best Answer-推荐答案


像 tableViewCell 一样为 header 和设计制作一个 customCell。

enter image description here

设计是如何完成的:

SMS EMAIL 和 PUSH NOTIFICATION 被封装在一个 stackView 中,并带有 TYPE 标签。

这是层次结构。

enter image description here

这就是Type(2/3)的布局设计。自己准确计算。

enter image description here

这是用于stackView的。

enter image description here

两者都是带有superView(即单元格)的自动布局

堆栈 View :

enter image description here

对于 TYPE 标签。

enter image description here

将此单元格插入为 tableView 的 headerView。

怎么做?

在 viewDidLoad 中:

tableView.register(UINib.init(nibName: String(describing: TableHeader.self), bundle: nil), forCellReuseIdentifier: "headerCell")

在你各自的 View Controller 中添加这两个函数。

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let cell = tableView.dequeueReusableCell(withIdentifier: "headerCell") as! TableHeader
    return cell
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 58
}

这是输出:

enter image description here

对于 iOS 8:

StackView 不存在,所以我们需要使用 UIView。因为解释自动布局很棘手,所以我只是分享了我的项目,这更容易理解。您可以从 here 结帐

不使用 StackView 的输出如下:

已拍摄 2 次。已给出颜色以便更好地理解。

enter image description here

关于ios - 在 UITableView 中使用动态标签宽度管理自动标题高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44411349/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4