0

I have a very peculiar situation and want to know why its happening. I have an edit box and button in a view that I put into a tableview's tableHeaderView property. I call this view InputToListCell.

Now when the view extends UIView I get the following:

enter image description here

i.e all I change in the code is:

class InputToListCell: UIView{
   //Code Here
}

I then change InputToListCell to extend UITableViewCell and get the following:

enter image description here

i.e

class InputToListCell: UITableViewCell{
   //Code Here
}

Why is this behaviour occurring? I cant see why because UITableViewCell extends UIView. Any thoughts?

Update:

Based on a comment made here are the constraints for the InputToListCell:

enter image description here

I basically pin both the edit text's and Add buttons constraints to the margin, except for the edit text's trailing value.

Community
  • 1
  • 1
user481610
  • 3,230
  • 4
  • 54
  • 101

1 Answers1

0

In short

Use UITableViewCell for table view elements.

self.tableView.tableHeaderView =
    tableView.dequeueReusableCellWithIdentifier("sectionIdentifier")

Discussion

Using UITableViewCell objects for all table view elements not only provide an umbrella behavior when presented inside a UITableView, but will also allow loading from a .storyboard or .xib, an added bonus and cohesion.

Thus, even though tableHeaderView (and viewForHeaderInSection for that matter) is informally just a UIView, you can return a UITableViewCell. According to this post, to take advantage of Autolayout in tableHeaderView, you need to do a bit of gymnastics:

if let tableHeaderView = tableView.dequeueReusableCellWithIdentifier("tableHeaderViewIdentifier") {
    tableHeaderView.setNeedsLayout()
    tableHeaderView.layoutIfNeeded()

    let height = tableHeaderView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
    var frame = tableHeaderView.frame

    frame.size.height = height
    tableHeaderView.frame = frame
    self.tableView.tableHeaderView = tableHeaderView
}

From a different post:

Two Section Headers


For a complete example on how to use .storyboard or .xib for headers, including an Xcode project, see https://stackoverflow.com/a/32261262/218152

Community
  • 1
  • 1
SwiftArchitect
  • 47,376
  • 28
  • 140
  • 179