簡體   English   中英

如何快速創建動態自調整高度 UITableViewCell?

[英]How to create dynamic self-sizing height UITableViewCell in swift?

嘿,我有一個 tableview 控制器,我想用標簽和 ImageViews 創建動態單元格高度。 我嘗試了類似下面的方法,但它對我不起作用。 代碼錯誤在哪里。 任何的想法 ?

class NotificationsPageController: UITableViewController{

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.register(NotificationCell.self, forCellReuseIdentifier: notCell)
    view.backgroundColor = .black
    tableView.estimatedRowHeight = 60
}

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableView.automaticDimension
}

    override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
      return 60
  }

 class NotificationCell: UITableViewCell {

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
      super.init(style: style, reuseIdentifier: reuseIdentifier)
   backgroundColor = UIColor(red: 18/255, green: 18/255, blue: 18/255, alpha: 1)

    setNotificationAnchors()

}

fileprivate func setNotificationAnchors() {

    addSubview(notiType)
    notiType.anchor(top: topAnchor, left: leftAnchor, bottom: nil, right: rightAnchor, paddingTop: 4, paddingLeft: 6, paddingBottom: 0, paddingRight: 20, width: 0, height: 0)
    //notiType.centerYAnchor.constraint(equalTo: notiImage.centerYAnchor).isActive = true



    addSubview(notiImage)
    notiImage.anchor(top: nil, left: nil, bottom: nil, right: rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 4, width: 0, height: 0)
    notiImage.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true



}

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
}

首先,我強烈建議您了解約束和自動布局的工作原理。 您發布的代碼表明您正在使用.anchor(top:left:bottom:right:...)類型的“約束助手”這一事實表明您還不了解它。

所以,這里有一個簡單的例子。 請注意,這不是一個完整的實現,但它應該讓您朝着正確的方向前進:

class NotificationCell: UITableViewCell {

    let notiType: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.numberOfLines = 0
        return v
    }()

    let notiImage: UIImageView = {
        let v = UIImageView()
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        backgroundColor = UIColor(red: 18/255, green: 18/255, blue: 18/255, alpha: 1)

        setNotificationAnchors()

    }

    fileprivate func setNotificationAnchors() {

        contentView.addSubview(notiType)
        contentView.addSubview(notiImage)

        let g = contentView.layoutMarginsGuide

        NSLayoutConstraint.activate([

            // constrain label Top, Leading, Bottom to contentView margins
            notiType.topAnchor.constraint(equalTo: g.topAnchor, constant: 0.0),
            notiType.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 0.0),
            notiType.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: 0.0),

            // constrain image view Right and centerY to contentView margins
            notiImage.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: 0.0),
            notiImage.centerYAnchor.constraint(equalTo: g.centerYAnchor, constant: 0.0),

            // guessing square (1:1 ratio) image view, 24 x 24
            notiImage.widthAnchor.constraint(equalToConstant: 24.0),
            notiImage.heightAnchor.constraint(equalTo: notiImage.widthAnchor),

            // leave 8-pts space between label and image view
            notiType.trailingAnchor.constraint(equalTo: notiImage.leadingAnchor, constant: -8.0),

        ])

        // during development, so we can easily see the element frames
        notiType.backgroundColor = .cyan
        notiImage.backgroundColor = .red

    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class ExampleTableViewController: UITableViewController {

    let notCell = "notCell"

    let theData: [String] = [
        "Single line label.",
        "This lable will have enough text that it will need to wrap onto multiple lines.",
        "Another single line cell.",
        "Here is a description of a table view cell: Defines the attributes and behavior of cells in a table view. You can set a table cell's selected-state appearance, support editing functionality, display accessory views (such as a switch control), and specify background appearance and content indentation.",
        "This is the fifth row.",
    ]

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.register(NotificationCell.self, forCellReuseIdentifier: notCell)
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return theData.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: notCell, for: indexPath) as! NotificationCell

        cell.notiType.text = theData[indexPath.row]

        // set image here...
        //cell.notiImage.image = ...

        return cell
    }

}

結果 - 多行標簽(青色背景)和 24x24 圖像(紅色背景):

在此處輸入圖片說明

順便說一句......關於這個的分步教程可以在很多很多地方找到 - 有點難以認為你搜索過並且找不到這樣的東西。

請按照以下步驟操作:

在 ViewDidLoad 中添加以下幾行

tableView.dataSource = self
tableView.delegate = self

// Set automatic dimensions for row height
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = UITableViewAutomaticDimension

XIBCell如果您有標簽更新numberOLines = 0並使lineBreakMode = truncateTail

topbottomrightleft約束更新到其superView

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM