SnapKit-UITableView的高度不会随单元格的动态内容而变化

时间:2018-10-09 20:32:06

标签: ios swift uikit tableview snapkit

我是SnapKit的初学者,我想用SnapKit实现UITableViewController,每行有两个UILabel,其中一个是Title,另一个是Value。 我的问题是UITableView中的行高不会根据每一行的内容而改变。 这是我的代码:

ViewController类:

TextBox

CustomCell类:

import UIKit
import SnapKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

// MARK: Property List
var list: NSMutableArray?
let myTableView: UITableView = {
   let table = UITableView()
    return table
}()

//MARK: Life Cycle
override func viewDidLoad() {
    super.viewDidLoad()
    self.myTableView.rowHeight = UITableView.automaticDimension
    self.myTableView.estimatedRowHeight = 100
    title = "TableView Page"
    setup()
    setupViews()

}

// MAKR: Setup View
func setup() {
    self.view.backgroundColor = .white
    navigationController?.navigationBar.prefersLargeTitles = true
}

func setupViews () {
    self.view.addSubview(myTableView)
    myTableView.snp.makeConstraints { make in
        make.top.left.bottom.right.equalTo(10)
    }
    myTableView.register(CustomCell.self, forCellReuseIdentifier: CustomCell.customCell)
    myTableView.delegate = self
    myTableView.dataSource = self
}

// MARK: TableView DataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 10
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: CustomCell.customCell, for: indexPath) as! CustomCell
    cell.title.text = "title is lognest??"
    cell.value.text = (indexPath.row % 2 == 0) ?
     "longest value longest value longest value longest value longest value longest value longest value for text"
        : "short value"
    cell.title.snp.makeConstraints { (make) in
        make.top.equalTo(cell.value.snp.top)
        make.left.equalTo(20)
        make.trailing.equalTo(cell.value.snp.leading)
    }
    cell.value.snp.makeConstraints { (make) in
        make.right.equalTo(-20)
        make.top.equalTo(cell.title.snp.top)
        make.bottom.equalTo(-10)
    }

    NSLog("value height is: \(cell.value.frame.height)")
    NSLog("cell height is: \(cell.frame.height)")
        return cell;
    }    
}

这是控制台日志:

  

snapkitTest [26345:1387159]单元格高度是:44.0
  snapkitTest [26345:1387159]值的高度是:0.0

Screen Shot of TableView on iPhone XR

1 个答案:

答案 0 :(得分:2)

1-您必须将标签添加到

self.contentView.addSubview(title)

2-您需要将底部约束设置为contentView

title.snp.makeConstraints { (make) -> Void in
        make.trailing.equalTo(value.snp.leading)
        make.top.equalTo(self.contentView.snp.top).inset(10)
        make.left.equalTo(20)
    }
value.snp.makeConstraints { (make) -> Void in
        make.right.equalTo(-40)
        make.top.equalTo(self.contentView.snp.top).inset(10)
        make.bottom.equalTo(-10)
    }

也将此约束转移到单元格自定义类的init,以免在tableView的每个滚动中都重新添加约束