代码之家  ›  专栏  ›  技术社区  ›  Moritz

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

  •  2
  • Moritz  · 技术社区  · 9 年前

    UITableViewAutomaticDimension 对于像120这样的任意值,它看起来或多或少像我想要的。

    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)
        ])
    }
    

    | 120 :

    <code>UITableViewAutomaticDimension</code> | <code>120</code>

    1 回复  |  直到 9 年前
        1
  •  3
  •   mag_zbc    9 年前

    问题是约束-将约束添加到单元格的子视图,但不添加到contentView。忽略了的高度约束 usernameLabel commentLabel contentView 内容视图 可以推断其大小,默认为 44.0 ,如上所述 here

    用户名标签 和底部约束 评论标签

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

    编辑

    推荐文章