简体   繁体   中英

Dynamically Changing all of the Uitableviewcells height to fill the uitableview in swift

I have been having an issue for quite some time with regards to an ios app I have been building in swift. I have a Uitableview ,with dynamic properties, embedded within my view controller. And what I want to do is size all of the cells to fill the table view. I have tried:

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    tableView.reloadData()
    let height = tableView.contentSize.height
    return height
}

but this just returned zero for the height of the uitableview.

Help would be very appreciated.

You don't want to call reloadData() from this delegate method, since this method is getting called because the data is being reloaded.

In fact, you don't want to use this method at all if all of your cells are going to be the same height. Just set the table view's rowHeight property.

Assuming this is happening from a view controller, I'd override viewDidLayoutSubviews() to get notified when the table view size changes and set the row height there:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    tableView.rowHeight = tableView.bounds.height
}

You may or may not need to add reloadData() there to get the table view to update. Try it without it first. Setting the row height may automatically trigger a reload.

Also notice that I don't use contentSize to get the height. That's the height of all of the cells, and it's determined by the row height you set. So again, using it gets a little circular.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM