Bullionist
Bullionist

Reputation: 2200

Get RowHeight of each row in UITableView Swift

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

Answers (5)

The functional way:

 let sum = tableView.visibleCells.map( { $0.bounds.height } ).reduce(0,+)
 print("Height:\(sum)")

Upvotes: 3

Kegham K.
Kegham K.

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

Alex Haas
Alex Haas

Reputation: 2147

Swift 4:

var height: CGFloat = 0
for cell in tableView.visibleCells {
    height += cell.bounds.height
}

Upvotes: 24

Patrick Lynch
Patrick Lynch

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

Teddy Koker
Teddy Koker

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

Related Questions