【发布时间】:2019-01-23 09:03:02
【问题描述】:
这是我想做的UITableView:
为了实现这一点,我将cell的contentView分成了三个部分。
1 - fromView:包含开始时间和班级类型。高度将是 contentView
的 30%2 - infoView:包含时钟图像、班级名称和教授姓名。高度将是contentView 的 40%。
3 - toView:包含结束时间和位置。高度将是剩余的空间(30%)。
首先,在详细介绍之前,我决定只展示这个容器。为了理解一个问题,我画了它们(分别是绿色、红色、蓝色)。
在将它们添加到contentView 之后,以下是我对这些容器的约束:
fromView.easy.layout(Top(), Left(), Right(), Height(*0.3).like(contentView))
infoView.easy.layout(Top().to(fromView), Left(), Right(), Height(*0.4).like(contentView))
toView.easy.layout(Top().to(infoView), Left(), Right(), Bottom())
似乎一切都是正确的。启动后,我以为我会看到它们,但发生了这样的事情:
我认为单元格不知道它需要多大,所以我决定实现以下功能:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 150
}
在此之后,UITableView 比以前更正确地显示了容器。但是,我计划在该容器中添加一些UILabels 和其他views(看第一张图片)。换句话说,我不知道一个单元格需要有多大。它需要是一种动态的。无论如何,我尝试将这些标签添加到容器中,也许在那之后,一个单元格会计算出高度。这是我的做法:
func setupViews() {
fromView.addSubviews(fromTime, classType)
toView.addSubviews(toTime, room)
infoView.addSubviews(clockImage, teacherName, subjectName)
contentView.addSubviews(toView, fromView, infoView)
}
func setupConstraints() {
fromView.easy.layout(Top(), Left(), Right(), Height(*0.3).like(contentView))
infoView.easy.layout(Top().to(fromView), Left(), Right(), Height(*0.4).like(contentView))
toView.easy.layout(Top().to(infoView), Left(), Right(), Bottom())
fromTime.easy.layout(CenterY(), Left(8))
fromTime.setContentHuggingPriority(.required, for: .horizontal)
fromTime.setContentCompressionResistancePriority(.required, for: .horizontal)
classType.easy.layout(CenterY(), Left(8).to(fromTime))
clockImage.easy.layout(CenterY(), Left(16), Width(24), Height(24))
subjectName.easy.layout(CenterY(-8), Left().to(classType, .left), Right())
teacherName.easy.layout(Top(8).to(subjectName), Left().to(subjectName, .left), Right())
toTime.easy.layout(CenterY(), Left(8))
toTime.setContentHuggingPriority(.required, for: .horizontal)
toTime.setContentCompressionResistancePriority(.required, for: .horizontal)
room.easy.layout(CenterY(), Left(8).to(toTime))
}
但不管怎样,问题又出现了:
我认为,问题是我根据contentView 的高度给容器指定高度,但contentView 不知道它的高度。但我也不知道它需要有什么高度,因为它需要根据标签的大小而定。那么,如何解决这个问题呢?
【问题讨论】:
标签: ios uitableview autolayout