Reputation: 3428
Is there any way by which I can get row height of each row in a UITableView
. I have a UITableView
which contains data which is dynamic, and I am using
self.tableView.rowHeight = UITableViewAutomaticDimension
to make dynamic row heights.
But I want to change height of overall UITableView
as well, for that I need height of all the rows after reload of data.
I tried using
self.tableView.layoutIfNeeded()
self.tableViewHeightContraint.constant = self.tableView.contentSize.height
But due to unknown reason it is giving me height less than what exactly it has, after I add 3 or 4 records in UITableView
so thinking of other way around. To calculate height of each rows and then summing them up.
I am doing in Xcode 7.2, iOS 9 and Swift 2
Upvotes: 1
Views: 6534
Reputation: 5569
NOTE: my section array stores the rows in the .data var
let heightOfAllRows:CGFloat = sections.enumerated().map { arg -> [(section:Int,row:Int)] in
return arg.element.data.indices.map{ i in
(section:arg.offset,row:i)
}
}.flatMap{$0}.reduce(0){
return $0 + self.tableView(self, heightForRowAt: .init(row: $1.row, section: $1.section))
}
Upvotes: 0
Reputation: 1
Maybe the table is not resizing its content, so if you try using [self. tableView layoutSubviews];
to force the resizing, it may work. [self. tableView layoutIfNeeded];
not necessarily forces the update.
Upvotes: 0
Reputation: 1803
This is because self.tableView.contentSize.height
returns number of rows * estimatedRowHeight
, which is not equivalent to actual height of the table view. What you need is to get the individual cell heights through visibleCells
, then sum those up to get the table view's height.
Refer to this for the answer: https://stackoverflow.com/a/40081129/4076956
Upvotes: 0
Reputation: 4281
var dictionaryOfCellHeight = [Int : CGFloat]()
var dataArray = [String]()
func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
if dictionaryOfCellHeight[indexPath.row] == nil
{
var frame : CGRect = tableView.rectForRowAtIndexPath(indexPath)
if indexPath.row == dataArray.count
{
dictionaryOfCellHeight[indexPath.row] = frame.size.height
//calculate total height and reload table
}
else
{
dictionaryOfCellHeight[indexPath.row] = frame.size.height
}
}
}
Upvotes: 2
Reputation: 776
You can use this
CGRect frame = [tableView rectForRowAtIndexPath:indexPath];
NSLog(@"row height : %f", frame.size.height);
Using frame.size.height
you can get height of particular row
Upvotes: 0
Reputation: 932
To change the height of Tableview
, you don't need to calculate the height of all UITableViewCell
s and set to TableView
.
Set the height
of each UITableViewCell
properly in heightForRowAtIndexPath
method. This will automatically set the scrollable height to your Tableview
Upvotes: 0