rodrigoalvesvieira
rodrigoalvesvieira

Reputation: 8062

Get UITableView cell height

I have an UIViewController that implements both UITableViewDelegate and UITableViewDataSource and I want to load the screen a bit scrolled down (starting from the 2nd cell). In this case, I tried to set tableView.contentOffset to a CGPointMake using a hardcoded height, which was the same value I set in the Storyboard for my cell.

However, I want to dynamically read the height. In my table view every cell has the same size, how can I get its height given that in my controller I have my UITableView instance?

Here is my code:

@IBOutlet var tableView: UITableView!

override func viewDidLoad() {
    // Here instead of 88.0 I wanted something like tableView.cellHeight.
    // Is there something like it? Anyone?

    tableView.contentOffset = CGPointMake(0.0, 88.0)
}

Upvotes: 2

Views: 7965

Answers (2)

kellanburket
kellanburket

Reputation: 12853

If you have static UITableView cells use:

 var height = tableView.rowHeight

If you have dynamic cells, you'll have to get it from your UITableViewDelegate using an indexPath, in your case, your UIViewController:

var indexPath = NSIndexPath(row: yourRow, section: yourSection)
var height = tableView(tableView, heightForRowAtIndexPath: indexPath)

If you've set an estimatedRowHeight you can also check that variable (but it will be zero if you haven't):

var height = tableView.estimatedRowHeight

Upvotes: 0

matt
matt

Reputation: 536047

The property you're looking for is called rowHeight. So ask for tableView.rowHeight.

Here are the UITableView docs:

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableView_Class/#//apple_ref/occ/instp/UITableView/rowHeight

They can be very helpful in these situations.

However, I'm not convinced that this is what you really need; it depends on what you mean by "I want to load the screen a bit scrolled down."

Upvotes: 5

Related Questions