3

I can't figure out why I can't get my section header heights to adjust based on the amount of text.

Most information I've found on this give the following steps on how to make cell row height adjust according to the amount of text:

  1. Add label to tableView cell in storyboard and set automatic constraints to label.
  2. Set number of lines to 0 in Attributes Inspector.
  3. Add the following code to swift file in ViewDidLoad:

    tableView.estimatedRowHeight = 50.0
    tableView.rowHeight = UITableViewAutomaticDimension
    

This works perfectly for me when making cell rows with dynamic heights but I can't get it to work with section headers.

I thought it would be as simple as adding:

tableView.sectionHeaderHeight = UITableViewAutomaticDimension;
tableView.estimatedSectionHeaderHeight = 50.0;

But that doesn't work. I know that code specifying row height will cancel out the Auto Layout constraints so I think a problem might be in some code I have that makes the sections expand/collapse on tap gesture, and it has an image (of an arrow that points up/down based on whether the section is expanded or collapsed). This is what I think may be causing the problem:

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    //recast your view as a UITableViewHeaderFooterView
    let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
    header.contentView.backgroundColor = UIColor.colorWithHexString(hexStr: "#4f9c25")
    header.textLabel?.textColor = UIColor.white


    if let viewWithTag = self.view.viewWithTag(kHeaderSectionTag + section) {
        viewWithTag.removeFromSuperview()
    }

    let borderTop = UIView(frame: CGRect(x:0, y:0, width: tableView.bounds.size.width, height: 1.0))
    borderTop.backgroundColor = UIColor.self.init(red: 5/255, green: 16/255, blue: 28/255, alpha: 1.0)
    header.addSubview(borderTop)


    let headerFrame = self.view.frame.size
    let theImageView = UIImageView(frame: CGRect(x: headerFrame.width - 32, y: 13, width: 18, height: 18));
    theImageView.image = UIImage(named: "Chevron-Dn-Wht")
    theImageView.tag = kHeaderSectionTag + section
    header.addSubview(theImageView)


    // make headers touchable
    header.tag = section
    let headerTapGesture = UITapGestureRecognizer()
    headerTapGesture.addTarget(self, action: #selector(WeedsControlledVC.sectionHeaderWasTouched(_:)))
    header.addGestureRecognizer(headerTapGesture)
}

And if that isn't the problem, I've also tried the suggestions in the following thread but I couldn't get it to work either.

Setting tableHeaderView height dynamically

Any ideas what I'm doing wrong?

DrewDog
  • 35
  • 1
  • 9

0 Answers0