Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set TableView height by the number or rows

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 flexible - by that I mean, for example: if I got 4 rows in the TableView and each TableView row height is 22 so the TableView height will be 88. Another example: number of rows: 2 row height = 22 TableView will be 44.

How can I make it?

like image 957
Eliko Avatar asked Aug 01 '15 10:08

Eliko


People also ask

How can I get UITableView height?

Use contentSize. height property of UITableView . I think you want to set the whole tableview with content size and then set the scrollview size related content of UITableView and for this use bellow code... After add data or reloadData in UITableView just set bellow code..

How does a Tableview work?

Table views in iOS display rows of vertically scrolling content in a single column. Each row in the table contains one piece of your app's content. For example, the Contacts app displays the name of each contact in a separate row, and the main page of the Settings app displays the available groups of settings.


2 Answers

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()
}
like image 60
Sohil R. Memon Avatar answered Oct 29 '22 00:10

Sohil R. Memon


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.

like image 27
Mr. JD Agrawal Avatar answered Oct 29 '22 01:10

Mr. JD Agrawal