xcode 如何调整XIB单元格的大小以显示2个标签?

j2qf4p5b  于 2022-12-14  发布在  其他
关注(0)|答案(2)|浏览(151)

在过去的3个小时里,我一直在用头撞墙,试图弄清楚这个问题。在看了无数的教程之后,我似乎仍然不能弄清楚为什么这个XIB单元格不能在tableview上显示两个标签。
XIB文件:

它一直显示为:

我就是不明白。我已经尝试了所有的方法,设置高度约束、距离约束、堆栈视图,但是没有任何方法可以让底部的第二个标签显示在表格视图单元格中。这里是否有什么明显的东西我遗漏了?

hrysbysz

hrysbysz1#

好吧,这绝对是乏味的,但我找到了,通过随机复制和粘贴在线代码位,直到一些工作。

override func awakeFromNib() {
    super.awakeFromNib()
    NSLayoutConstraint.activate([
        titleLabel.topAnchor.constraint(equalTo: contentView.topAnchor,constant: 5),
        titleLabel.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor),
        titleLabel.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor),
        titleLabel.bottomAnchor.constraint(equalTo: projLabel.topAnchor),
        
        
        projLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor),
        projLabel.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor),
        projLabel.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor),
        projLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
    ])

最终结果:

8zzbczxx

8zzbczxx2#

试试这个:
在情节提要-〉身份检查器中选择TableView

  • 将行高设置为“自动”(留空)
  • 将估计值设置为某个值(例如150)

在单元格类上实现此方法(例):

override func sizeThatFits(_ size: CGSize) -> CGSize {
    // 1) Set the contentView's width to the specified size parameter
    contentView.pin.width(size.width)

    // 2) Layout the contentView's controls
    layout()

    // 3) Returns a size that contains all controls
    return CGSize(width: contentView.frame.width, height: adsViewsCount.frame.maxY + padding)
}

使用UITableViewDatasource实现此功能:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    // The UITableView will call the cell's sizeThatFit() method to compute the height.
    // WANRING: You must also set the UITableView.estimatedRowHeight for this to work.
    return UITableView.automaticDimension
}

相关问题