0

I am having a view at the top of my tableViewController.
The view is called viewBackground.
It is there to show the post the user clicked on and the table cells will show the comments.

What I want to do is to resize the viewBackground depending on the size of the label theLabel.
I have done this in the cells by setting the label in the cells to 0 lines and by implementing this little code :

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 205

How do I do the same with my viewBackground?

This is a picture of the tableView:

enter image description here

D. Finna
  • 467
  • 2
  • 7
  • 19

3 Answers3

0

I suggest to make a header for your current tableView -instead of adding an external view above it-, and then you can follow this answer, it should helps you of how you can calculate the label's string height and returning it in the tableView(_:heightForRowAt:) method.

Hope this helped.

Community
  • 1
  • 1
Ahmad F
  • 30,560
  • 17
  • 97
  • 143
  • I think I am making a header, by adding the view? – D. Finna Oct 19 '16 at 10:01
  • yes, make it simpler by adding a new cell to your tableView and implement [viewForHeaderInSection](https://developer.apple.com/reference/uikit/uitableviewdelegate/1614901-tableview) method. Please check the url in the answer, it should help you to calculate the height of the label, but instead of referenceSizeForHeaderInSection, it should be only the height ([heightForHeaderInsSection](https://developer.apple.com/reference/uikit/uitableviewdelegate/1614998-tableview)) – Ahmad F Oct 19 '16 at 10:23
  • anyway, if you couldn't understand it at all, just make sure that using [viewForHeaderInSection](https://developer.apple.com/reference/uikit/uitableviewdelegate/1614901-tableview) is fit for your case and shoot a comment, I'll be glad to help :) – Ahmad F Oct 19 '16 at 10:32
0

You can create table view with two sections. First section will contain selected post; second section - comments. If you need, i can provide some code.

Maksym Musiienko
  • 1,248
  • 8
  • 16
0

Added this code and it helped!

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    if let headerView = tableView.tableHeaderView {
        let height = headerView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
        var headerFrame = headerView.frame

        //Comparison necessary to avoid infinite loop
        if height != headerFrame.size.height {
            headerFrame.size.height = height
            headerView.frame = headerFrame
            tableView.tableHeaderView = headerView
        }
    }
}
D. Finna
  • 467
  • 2
  • 7
  • 19