Aashish Nagar
Aashish Nagar

Reputation: 1227

viewForHeader with dynamic height?

I am returning a view with dynamic height for viewForHeader in table views.I have 2 section.But I am getting a view that is for header section 1 in section 0 and for section 1 no view is coming blank space is coming.Below is the code.

        tblList.estimatedSectionHeaderHeight = 100
        tblList.sectionHeaderHeight = UITableViewAutomaticDimension


        func numberOfSections(in tableView: UITableView) -> Int {
            return 2
        }

       func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        print("Section: \(section)")
            let view = UIView()
            let lbl = UILabel()
           view.backgroundColor = UIColor.LGColor()

            view.translatesAutoresizingMaskIntoConstraints  = false
            lbl.translatesAutoresizingMaskIntoConstraints = false
            view.addSubview(lbl)
            lbl.font = UIFont.subHeadline

            view.addConstraint(NSLayoutConstraint(item: lbl, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 3))

            view.addConstraint(NSLayoutConstraint(item: lbl, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 10))

            view.addConstraint(NSLayoutConstraint(item: lbl, attribute: .trailing, relatedBy: .lessThanOrEqual, toItem: view, attribute: .trailing, multiplier: 1, constant: -10))

            view.addConstraint(NSLayoutConstraint(item: lbl, attribute: .height, relatedBy:.greaterThanOrEqual, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 21))

            view.addConstraint(NSLayoutConstraint(item: view, attribute: .bottom, relatedBy: .equal, toItem: lbl, attribute: .bottom, multiplier: 1, constant: 3))


   view.addConstraint(NSLayoutConstraint(item: view, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: tableView.frame.size.width))

        if section == 0 {
            view.backgroundColor = .red
        } else {
            view.backgroundColor = .yellow
        }
        return view
}

Upvotes: 1

Views: 185

Answers (2)

Sergei Navka
Sergei Navka

Reputation: 104

It's happens because you set translatesAutoresizingMaskIntoConstraints = false for header view, remove this line

Its remove constraints created in TableView and two views have origin point {0, 0}

enter image description here

Upvotes: 1

Amal T S
Amal T S

Reputation: 3405

It is because you set view.translatesAutoresizingMaskIntoConstraints = false, comment that line and check if you can see both sections

Upvotes: 1

Related Questions