根据表格视图单元格的数量设置UITableView的超级视图高度

时间:2019-03-05 13:39:50

标签: swift uitableview

我的UITableView嵌入在UIView中,我希望该超级视图的高度根据表视图拥有的UITableViewCell的数量而变化。

这意味着,如果tableView有1个单元格,UIView将是此单元格的大小,如果有2个单元格,则UIView将增长到2个单元格的大小。

2 个答案:

答案 0 :(得分:1)

我会在UIView的{​​{1}}的基础上再添加一个UITableViewCell。然后我将contentView设置为真实的backgroundColor

enter image description here

答案 1 :(得分:0)

如果您使用的是自动布局约束,则只需更新UITableView的高度约束本身即可。

以下是基本步骤:

  1. 子类UITableView:

    class CustomTableView: UITableView {
    
        var maximumTableViewHeight: CGFloat = UIScreen.main.bounds.size.height
    
        private var heightConstraint: NSLayoutConstraint!
    
        override func reloadData() {
           super.reloadData()
            self.heightConstraint.constant = min(self.contentSize.height, maximumTableViewHeight)
        }
    
        override func awakeFromNib() {
            super.awakeFromNib()
    
            self.heightConstraint = NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil,
                                                       attribute: .notAnAttribute, multiplier: 1, constant: 0)
            self.addConstraint(heightConstraint)
        }
    
    }
    
  2. 故事板具有我们的子类CustomTableView

Storyboard

  1. 然后是您的视图控制器:

    class ViewController: UIViewController, UITableViewDataSource {
    
        @IBOutlet var tableView: CustomTableView!
        private let cellIdentifier = "Cell"
    
        var dataSource: [Int] = [1, 2, 3] {
            didSet {
                self.tableView.reloadData()
            }
        }
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            self.tableView.dataSource = self
            self.tableView.maximumTableViewHeight = 400 // Adjust as per your max height
        }
    
        @IBAction func addCell(_ sender: Any) {
            let count = self.dataSource.count + 1
            self.dataSource.append(count)
    
            let scrollToIndexPath = IndexPath(row: count - 1, section: 0)
            DispatchQueue.main.async {
                self.tableView.scrollToRow(at: scrollToIndexPath, at: .bottom, animated: false)
            }
        }
    
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return self.dataSource.count
        }
    
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            var cell: UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
            if cell == nil {
                cell = UITableViewCell(style: .default, reuseIdentifier: cellIdentifier)
            }
    
            cell.textLabel?.text = "Value: " + String(dataSource[indexPath.row])
            return cell
        }
    
    }
    

结果是:

enter image description here

注意红色区域,即UIView的父UITableView

相关问题