由于插入 UITableViewAutomaticDimension 返回的单元格很小

Since inserting UITableViewAutomaticDimension returned cells are tiny

我正在为我的应用开发评论部分,并希望我的单元格自动调整大小。如果我用 120 之类的任意值替换 UITableViewAutomaticDimension,它看起来或多或少就像我想要的那样。

但是,如果我将其保留在 UITableViewAutomaticDimension,则返回的单元格实际上很小。我将在最后添加一张图片,显示两种方式的外观(左:UITableViewAutomaticDimension,右:rowHeight = 120)。我怎样才能解决这个问题?自从我 do 设置约束以来,我还没有发现任何人有类似的问题,这在很多情况下是自动调整大小问题的原因(子视图确实设置了 translatesAutoresizingMaskIntoConstraintsfalse).

我将提供您可能感兴趣的所有代码。它基本上就是一个标准的 table 视图,其中包含应该自动调整自身大小并使用约束的单元格。

非常感谢您的帮助!

评论单元格

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)

    setupViews()
}

func setupViews() {
    //all of these subviews have .translatesAutoresizingMaskIntoConstraints = false
    contentView.addSubview(profilePictureView)
    contentView.addSubview(usernameLabel)
    contentView.addSubview(commentLabel)

    let marginGuide = contentView.layoutMarginsGuide

    let viewWidth = UIScreen.main.bounds.width

    NSLayoutConstraint.activate([
        profilePictureView.heightAnchor.constraint(equalToConstant: 42),
        profilePictureView.widthAnchor.constraint(equalToConstant: 42),
        profilePictureView.leftAnchor.constraint(equalTo: marginGuide.leftAnchor),
        profilePictureView.topAnchor.constraint(equalTo: marginGuide.topAnchor, constant: -2),

        usernameLabel.leftAnchor.constraint(equalTo: profilePictureView.rightAnchor, constant: 16),
        usernameLabel.widthAnchor.constraint(equalToConstant: viewWidth - 66),
        usernameLabel.centerYAnchor.constraint(equalTo: profilePictureView.centerYAnchor, constant: -8),

        commentLabel.leftAnchor.constraint(equalTo: profilePictureView.rightAnchor, constant: 16),
        commentLabel.widthAnchor.constraint(equalTo: usernameLabel.widthAnchor),
        commentLabel.topAnchor.constraint(equalTo: usernameLabel.bottomAnchor, constant: 4)
    ])
}

UITableViewAutomaticDimension | 120:

问题是约束 - 您将约束添加到单元格的子视图,而不是 contentView。您省略了 usernameLabelcommentLabel 的高度限制 - 没错,它们将根据其内容调整大小。但是 contentView 不会调整大小,因为它不知道所需的大小。没有任何限制,contentView 可以从中推断出它的大小,它默认为 44.0,如 here 所述。

所以你需要做的是将顶部约束添加到 usernameLabel 并将底部约束添加到 commentLabel

usernameLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 0)
commentLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 0)

编辑
你好像已经有top anchor了,所以只要bottom anchor就够了。