Reputation: 2200
is there a way to get the row height for each row in an UITableView
in swift ? Please help. Thanks in advance.
Upvotes: 18
Views: 24183
Reputation: 9649
The functional way:
let sum = tableView.visibleCells.map( { $0.bounds.height } ).reduce(0,+)
print("Height:\(sum)")
Upvotes: 3
Reputation: 1614
You need the cell for a certain IndexPath
to calculate its bounds.
You can do it this way in any of the delegate functions of the UITableView
:
let row = tableView.cellForRow(at: indexPath)
let cellHeight = (row?.bounds.height)!
let cellWidth = (row?.bounds.width)!
Upvotes: 0
Reputation: 2147
Swift 4:
var height: CGFloat = 0
for cell in tableView.visibleCells {
height += cell.bounds.height
}
Upvotes: 24
Reputation: 2782
Cells only exist when they are visible, and you have access to them through the table view's visibleCells()
method.
for obj in tableView.visibleCells() {
if let cell = obj as? UITableViewCell {
let height = CGRectGetHeight( cell.bounds )
}
}
Upvotes: 3
Reputation: 984
I think this is what you are looking for. This assumes that "Cell" is the identifier of the given row, and indexPath is the index of the row in question.
let row = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)as! UITableViewCell
let height = row.bounds.height
Upvotes: 8