Set TableView height by the number or rows

前端 未结 9 1580
不思量自难忘°
不思量自难忘° 2021-01-31 10:40

I have got TableView in the MainstoryBoard and the number of rows is random every time. I want the height of the whole TableView to be fl

相关标签:
9条回答
  • 2021-01-31 11:28

    Take outlet of the Height Constraint of the parent view and assign it the height of table view's content + constant(extra height of other contents in the view)

    heightConstraintView.constant = tableView.contentSize.height + constantValue //use the value of constant as required.
    

    and write this code in the cellForRowAt method.

    0 讨论(0)
  • 2021-01-31 11:30

    You can change the UITableView height as per the contentSize as below:

    Swift 2.2

    tableView.frame = CGRectMake(tableView.frame.origin.x, tableView.frame.origin.y, tableView.frame.size.width, tableView.contentSize.height)
    

    Swift 3 or 4+

    tableView.frame = CGRect(x: tableView.frame.origin.x, y: tableView.frame.origin.y, width: tableView.frame.size.width, height: tableView.contentSize.height)
    

    and make sure you write the above line in viewDidAppear method

    You need to write the above line in viewDidLayoutSubviews also.

    Swift 2.2

    func viewDidLayoutSubviews(){
         tableView.frame = CGRectMake(tableView.frame.origin.x, tableView.frame.origin.y, tableView.frame.size.width, tableView.contentSize.height)
         tableView.reloadData()
    }
    

    Swift 3 or 4+

    func viewDidLayoutSubviews(){
         tableView.frame = CGRect(x: tableView.frame.origin.x, y: tableView.frame.origin.y, width: tableView.frame.size.width, height: tableView.contentSize.height)
         tableView.reloadData()
    }
    
    0 讨论(0)
  • 2021-01-31 11:34
    DispatchQueue.main.async {
        var frame = tableView.frame
        frame.size.height = tableView.contentSize.height
        tableView.frame = frame
    }
    

    OR

    DispatchQueue.main.async {
        self.TblViewHeightConstraint.constant = CGFloat((self.array.count) * 30)//Here 30 is my cell height
        self.TblView.reloadData()
    }
    
    0 讨论(0)
提交回复
热议问题