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

前端 未结 7 1414
野的像风
野的像风 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:01

    Extending @nova answer to swift 4

    tableViewSizeObservation = tableView.observe(\.contentSize) { [weak self] (tableView, _) in
       tableView.layer.removeAllAnimations()
       self?.tableViewHeightContraint.constant = tableView.contentSize.height
       UIView.animate(withDuration: 0.5) {
             self?.view.updateConstraints()
             self?.view.layoutIfNeeded()
       }
    }
    
    deinit {
        tableViewSizeObservation?.invalidate()
    }
    

提交回复
热议问题