【发布时间】: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