问题
Width of my headerView does not adapt to the width of the screen.
My viewForHeaderInSection
function:
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let cell = self.tableView.dequeueReusableCellWithIdentifier("sectionCell") as! sectionCell
cell.hint.text = "some name"
cell.tag = section
let singleTap = UITapGestureRecognizer(target: self, action: #selector(singleTapOnSection(_:)))
cell.addGestureRecognizer(singleTap)
let view = UIView(frame: cell.frame)
view.addConstraints(cell.constraints)
view.addSubview(cell)
return view
}
I must add cell to the UIView (or something similar) because i have hiding of row in the section. In my opinion i must add to "view" some constraints programmatically, but i dont know how
回答1:
Define a customView: UITableViewHeaderFooterView
class, and in viewDidLoad:
of View Controller write
tableView.registerClass(customView.classForCoder(), forHeaderFooterViewReuseIdentifier: "HeaderIdentifier")
And instead of dequeueing a cell, dequeue a UITableViewHeaderFooterView
(as it is the right way to do it).
This way you have to add auto layout in code or define it in a nib file, working with nibs and handling all kinds of things is kinda frustrating, if you're using this approach i suggest use this library NibDesignable.
回答2:
You should define headerview
with same width of tableview
and height what you require. don't give cell's height or width. If you are using storyborard for ui then drag uiview on tableview at upper side it will automatically set as headerview and then give top,leading,trailing and fix heigth constraints
and remove viewForHeaderInSection
method.
hope this will help :)
来源:https://stackoverflow.com/questions/36701095/viewforheaderinsection-incorrect-width