-1

セルに 2 つのラベルを追加し、スナップキットでこれらの制約を設定しました。問題は、セルを正しく展開できず、デフォルトの高さのままです。

titleLabel.snp.makeConstraints { (make) -> Void in
        make.top.equalTo(contentView.snp.top)
        make.bottom.equalTo(descriptionLabel.snp.top)
        make.left.equalTo(contentView.snp.left)
        make.right.equalTo(contentView.snp.right)
    }
    descriptionLabel.snp.makeConstraints { (make) -> Void in
        make.top.equalTo(titleLabel.snp.bottom)
        make.bottom.equalTo(contentView.snp.bottom)
        make.left.equalTo(contentView.snp.left)
        make.right.equalTo(contentView.snp.right)
    }

ご覧のように 4 つのエッジをマッピングしましたが、高さがこれらによって暗示されているわけではないことはわかっています。コンテンツが本質的に動的であり、さまざまな高さである可能性がある場合、どのように高さを適用できますか...

ラベルの設定は次のようになります。

 lazy var titleLabel: UILabel = {
    let titleLabel = UILabel()
    titleLabel.textColor = .green
    titleLabel.textAlignment = .center
    contentView.addSubview(titleLabel)
    return titleLabel
}()

lazy var descriptionLabel: UILabel = {
    let descriptionLabel = UILabel()
    descriptionLabel.textColor = .dark
    descriptionLabel.textAlignment = .center
    descriptionLabel.numberOfLines = 0
    contentView.addSubview(descriptionLabel)
    return descriptionLabel
}()
4

2 に答える 2

0

まず、サブクラス化された UITableViewCell クラスの初期化メソッドで contentView にサブビューを追加する必要があると思います。

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
           super.init(style: style, reuseIdentifier: reuseIdentifier)
           self.contentView.addSubview(titleLabel)
           self.contentView.addSubview(descriptionLabel)
}

次に、viewDidLoad メソッド (おそらく ViewController 内) に次の 2 行が追加されていることを確認します。

tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableView.automaticDimension

もちろん、必要に応じて EstimatedRowHeight を変更する必要があります。

言及する価値のあるもう1つのこと-これらの制約をより簡単に作成できます(SnapKitの機能を使用):

titleLabel.snp.makeConstraints { (make) -> Void in
    make.top.left.right.equalTo(contentView)
}
descriptionLabel.snp.makeConstraints { (make) -> Void in
    make.top.equalTo(titleLabel.snp.bottom)
    make.bottom.left.right.equalTo(contentView)
}
于 2018-11-23T00:38:42.663 に答える