0

Sample project: http://cl.ly/3f1R3t26091F

I have a UITextView inside my UITableView's header, and the text view holds variable-length content, and I'd like the table view header to be the correct size to display all of the content in the text view.

However, it does not. I'm following this question regarding how to set the height of a UITableView header automatically using Auto Layout, and it basically comes down to calculating the height of the view, then resetting it as the header again.

So in viewDidLayoutSubviews after I'm sure everything has been set up, I do:

override func viewWillLayoutSubviews() {
    super.viewDidLayoutSubviews()

    if !viewsSetUp {
        let numberOfWords = Int(arc4random_uniform(200))
        println("Number of words to generate: \(numberOfWords)")

        var text = "cat"

        for (var i = 0; i < numberOfWords; i++) {
            text += " cat"
        }

        text += "Should be able to see this: THE END"

        textView.text = text

        updateTableViewHeader()

        viewsSetUp = true
    }
}

And in it I call updateTableViewHeader to determine the height:

func updateTableViewHeader() {
    tableView.tableHeaderView = informationView
    informationView.setNeedsLayout()
    informationView.layoutIfNeeded()

    let informationViewHeight = informationView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height

    var newInformationViewFrame = informationView.frame
    newInformationViewFrame.size.height = informationViewHeight
    informationView.frame = newInformationViewFrame

    tableView.tableHeaderView = informationView
}

But my table view header is always way too short. How do I make it automatically size with the UITextView?

Community
  • 1
  • 1
Doug Smith
  • 29,668
  • 57
  • 204
  • 388
  • Try passing informationView.frame.size instead of UILayoutFittingCompressedSize to systemLayoutSizeFittingSize. Text needs to know the available width, otherwise it cannot possibly figure out how high the text should be. You may need to tell informationView that the text can have multiple lines. And changing the text in viewWillLayoutSubviews may be a bad idea. – gnasher729 Apr 27 '15 at 00:14
  • Tried the first suggestion, as well as moving it form viewWillLayoutSubviews to viewDidLoad and neither worked. – Doug Smith Apr 27 '15 at 00:19

0 Answers0