Set UITableView's height to the height of its content with Auto Layout

前端 未结 7 1413
野的像风
野的像风 2020-12-04 13:40

I have a View which has two labels and a Table View inside it. I want label 1 to always stay above my Table View and label 2, to be below the Table View. The problem is that

相关标签:
7条回答
  • 2020-12-04 14:07

    There is another way to do that. You can add an observer on table view contentSize variable, and self size when change in table view content.

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var tableHeightConstraint: NSLayoutConstraint!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.new, context: nil)
    }
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        tableView.layer.removeAllAnimations()
        tableHeightConstraint.constant = tableView.contentSize.height
        UIView.animate(withDuration: 0.5) {
            self.updateViewConstraints()
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题