gpt4 book ai didi

uitableview - UITAbleViewCell 中具有动态高度的多个 UILabel

转载 作者:可可西里 更新时间:2023-11-01 00:53:05 28 4
gpt4 key购买 nike

在一个空的 UITableViewCell 中,我有两个 UILabel 对齐方式如下:|--label1----label2--|。 两者 都将动态填充。我需要设置约束,使两个标签都保持居中对齐,但单元格的高度 由具有最多内容 的标签确定。到目前为止:

  • 标签的行数设置为0
  • ViewDidLoad 中:

    tableView.rowHeight = 40.0
    tableView.estimatedRowHeight = 40.0
  • UITableViewDelegate 方法:

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
    }

    func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
    }

    问题是我找不到合适的约束设置来实现这样的结果:

    |-------------------- ------一条长消息--|
    |--一条长消息------一条长消息--|
    |--一条长消息------ --一条长消息--|
    |--一条长消息------一条长消息--|
    |--一条长消息------一条长消息留言--|
    |----------------------------更长的消息--|



    |------------------------更长的消息--|
    |--消息-- ----------更长的消息--|
    |------------------------更长的消息--|

    有任何想法吗?我正在使用 Swift 1.2Xcode 6.3(和 Storyboard)谢谢!

最佳答案

为单元格添加(较低优先级)固定高度约束(例如 = 40)。

为每个标签添加顶部和底部约束。使顶部约束为固定边距(例如 = 8)。使底部约束成为(更高优先级)大于或等于约束(例如 >= 8)。

单元格的高度将由较高的标签决定,所有其他垂直约束仍将得到满足。

更新:

事实证明,您不需要单元格的固定高度约束,甚至不需要调整水平内容拥抱或压缩阻力优先级。

我将标签的上边缘和左边缘或右边缘固定到 superview.margin,= 0,并在标签之间添加了水平间距 >= 4。

我将标签的底部边缘固定到 superview.margin,>= 0。我还将两个标签的垂直压缩阻力优先级设置为 1000。

此时,我们已经设置了最低限度的必要约束。但是,如果两个标签都很长,一个标签将占据大部分宽度,迫使另一个标签变得非常窄。我任意向两个标签添加了一个宽度 >= 100 的约束以平衡两者。

Label constraints

-viewDidLoad 中启用自动调整大小,然后分配标签文本,并让单元格自行布局。没有必要覆盖自定义 UITableViewCell 中的任何内容。

self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 44.0;

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

cell.leftLabel.text = ...;
cell.rightLabel.text = ...;

[cell setNeedsLayout];
[cell layoutIfNeeded];

return cell;
}

Snapshot of tableView with dynamic side-by-side labels

关于uitableview - UITAbleViewCell 中具有动态高度的多个 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30267004/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com