ios - 如何制作具有动态高度的自定义 UITableViewCell?

标签 ios swift xcode uitableview

我的目标是制作这样的屏幕:

enter image description here

这是我用 StackView 和 Labels 实现的屏幕。 但现在,我想用 UITableView 来做到这一点。我的问题是 Cells 需要是动态的。因为文本可能与其他文本不同。 所以我开始用你的xib文件创建一个UITableViewCell(背景灰色是设计的)

enter image description here

Swift 文件

class CellCreateSaleVC: UITableViewCell {


    @IBOutlet weak var lblInfo: UILabel!
    @IBOutlet weak var imgClipboard: UIImageView!
    @IBOutlet weak var lblNomeCampo: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)


    }

}

带有 UITableView 的 ViewController

class CreateSaleViewController : UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableViewMenu: UITableView!
    let options : Int = 12


    override func viewDidLoad() {

        tableViewMenu.dataSource = self
        tableViewMenu.delegate = self
        tableViewMenu.register(UINib(nibName: "CellCreateSaleVC", bundle: nil), forCellReuseIdentifier: "CellCreateSale")

    }

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

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return options
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CellCreateSale") as! CellCreateSaleVC
        return cell
    }

}

但是我的结果是这样的: enter image description here

最佳答案

对于动态高度TableViewCell,您需要使用self-sizing table view cells ,您必须将 TableView 的 rowHeight 属性设置为 UITableViewAutomaticDimension。您还必须为 estimatedRowHeight 属性分配一个值。

tableView.estimatedRowHeight = 85.0
tableView.rowHeight = UITableViewAutomaticDimension

要定义单元格的高度,请向单元格 View 添加从 到 到底部边缘的约束。如果您的 View 具有固有的内容高度,系统将使用这些值。如果没有,您必须向 View 或内容 View 本身添加适当的高度约束。

enter image description here

注意:

Additionally, try to make the estimated row height as accurate as possible. The system calculates items such as the scroll bar heights based on these estimates. The more accurate the estimates, the more seamless the user experience becomes.

引用this使用自动布局动态单元高度的优秀堆栈溢出答案。和 raywendelich.com tutorial在自动调整表格 View 单元格大小上。

关于ios - 如何制作具有动态高度的自定义 UITableViewCell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50780893/

相关文章:

iphone - 按钮不会添加到 View 中

xcode - 无法使用类型为 '(String)' 的参数列表调用 <method>

ios - 如何将十六进制数组转换为 UIImage?

ios - block /方法可以互换吗?

吹气球的 iOS 动画

SwiftUI - SwiftUI 中是否有等效的 popViewController?

ios - 如果 UIButton 的大小是一定大小,如何更改它的大小

ios - 使对象居中,使垂直约束始终均匀

arrays - 在for循环中将多个对象添加到swift数组

ios - 如何在 ios 应用程序中合并两个半图像?