【问题标题】:Since inserting UITableViewAutomaticDimension returned cells are tiny由于插入 UITableViewAutomaticDimension 返回的单元格很小
【发布时间】:2018-01-04 15:42:04
【问题描述】:

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

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

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

非常感谢您的帮助!

评论单元

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:

【问题讨论】:

  • 我很确定这与约束有关。您是否有理由不在情节提要中执行这些操作?

标签: ios swift uitableview autoresize


【解决方案1】:

问题是约束 - 您将约束添加到单元格的子视图,而不是 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)

编辑
您似乎已经有了顶级锚,所以只要底部的就足够了。

【讨论】:

  • 我明白了,这是有道理的。但是,不需要为用户名标签设置topAnchor,因为已使用centerYAnchor 设置了topAnchor。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-14
  • 1970-01-01
  • 1970-01-01
  • 2016-05-19
相关资源
最近更新 更多