Swift - How creating custom viewForHeaderInSection, Using a XIB file?

78,431

Solution 1

The typical process for NIB based headers would be:

  1. Create UITableViewHeaderFooterView subclass with, at the least, an outlet for your label. You might want to also give it some identifier by which you can reverse engineer to which section this header corresponds. Likewise, you may want to specify a protocol by which the header can inform the view controller of events (like the tapping of the button). Thus, in Swift 3 and later:

    // if you want your header to be able to inform view controller of key events, create protocol
    
    protocol CustomHeaderDelegate: class {
        func customHeader(_ customHeader: CustomHeader, didTapButtonInSection section: Int)
    }
    
    // define CustomHeader class with necessary `delegate`, `@IBOutlet` and `@IBAction`:
    
    class CustomHeader: UITableViewHeaderFooterView {
        static let reuseIdentifier = "CustomHeader"
    
        weak var delegate: CustomHeaderDelegate?
    
        @IBOutlet weak var customLabel: UILabel!
    
        var sectionNumber: Int!  // you don't have to do this, but it can be useful to have reference back to the section number so that when you tap on a button, you know which section you came from; obviously this is problematic if you insert/delete sections after the table is loaded; always reload in that case
    
        @IBAction func didTapButton(_ sender: AnyObject) {
            delegate?.customHeader(self, didTapButtonInSection: section)
        }
    
    }
    
  2. Create NIB. Personally, I give the NIB the same name as the base class to simplify management of my files in my project and avoid confusion. Anyway, the key steps include:

    • Create view NIB, or if you started with an empty NIB, add view to the NIB;

    • Set the base class of the view to be whatever your UITableViewHeaderFooterView subclass was (in my example, CustomHeader);

    • Add your controls and constraints in IB;

    • Hook up @IBOutlet references to outlets in your Swift code;

    • Hook up the button to the @IBAction; and

    • For the root view in the NIB, make sure to set the background color to "default" or else you'll get annoying warnings about changing background colors.

  3. In the viewDidLoad in the view controller, register the NIB. In Swift 3 and later:

    override func viewDidLoad() {
        super.viewDidLoad()
    
        tableView.register(UINib(nibName: "CustomHeader", bundle: nil), forHeaderFooterViewReuseIdentifier: CustomHeader.reuseIdentifier)
    }
    
  4. In viewForHeaderInSection, dequeue a reusable view using the same identifier you specified in the prior step. Having done that, you can now use your outlet, you don't have to do anything with programmatically created constraints, etc. The only think you need to do (for the protocol for the button to work) is to specify its delegate. For example, in Swift 3:

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "CustomHeader") as! CustomHeader
    
        headerView.customLabel.text = content[section].name  // set this however is appropriate for your app's model
        headerView.sectionNumber = section
        headerView.delegate = self
    
        return headerView
    }
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 44  // or whatever
    }
    
  5. Obviously, if you're going to specify the view controller as the delegate for the button in the header view, you have to conform to that protocol:

    extension ViewController: CustomHeaderDelegate {
        func customHeader(_ customHeader: CustomHeader, didTapButtonInSection section: Int) {
            print("did tap button", section)
        }
    }
    

This all sounds confusing when I list all the steps involved, but it's really quite simple once you've done it once or twice. I think it's simpler than building the header view programmatically.


In matt's answer, he protests:

The problem, quite simply, is that you cannot magically turn a UIView in a nib into a UITableViewHeaderFooterView merely by declaring it so in the Identity inspector.

This is simply not correct. If you use the above NIB-based approach, the class that is instantiated for the root view of this header view is a UITableViewHeaderFooterView subclass, not a UIView. It instantiates whatever class you specify for the base class for the NIBs root view.

What is correct, though, is that some of the properties for this class (notably the contentView) aren't used in this NIB based approach. It really should be optional property, just like textLabel and detailTextLabel are (or, better, they should add proper support for UITableViewHeaderFooterView in IB). I agree that this is poor design on Apple's part, but it strikes me as a sloppy, idiosyncratic detail, but a minor issue given all the problems in table views. E.g., it is extraordinary that after all these years, that we still can't do prototype header/footer views in storyboards at all and have to rely on these NIB and class registration techniques at all.

But, it is incorrect to conclude that one cannot use register(_:forHeaderFooterViewReuseIdentifier:), an API method that has actively been in use since iOS 6. Let’s not throw the baby out with the bath water.


See previous revision of this answer for Swift 2 renditions.

Solution 2

Rob's answer, though it sounds convincing and has withstood the test of time, is wrong and always was. It's difficult to stand alone against the overwhelming crowd "wisdom" of acceptance and numerous upvotes, but I'll try to summon the courage to tell the truth.

The problem, quite simply, is that you cannot magically turn a UIView in a nib into a UITableViewHeaderFooterView merely by declaring it so in the Identity inspector. A UITableViewHeaderFooterView has important features that are key to its correct operation, and a plain UIView, no matter how you may cast it, lacks them.

  • A UITableViewHeaderFooterView has a contentView, and all your custom subviews must be added to this, not to the UITableViewHeaderFooterView.

    But a UIView mysteriously cast as a UITableViewHeaderFooterView lacks this contentView in the nib. Thus, when Rob says "Add your controls and constraints in IB", he is having you add subviews directly to the UITableViewHeaderFooterView, and not to its contentView. The header thus ends up incorrectly configured.

  • Another sign of the issue is that you are not permitted to give a UITableViewHeaderFooterView a background color. If you do, you'll get this message in the console:

    Setting the background color on UITableViewHeaderFooterView has been deprecated. Please set a custom UIView with your desired background color to the backgroundView property instead.

    But in the nib, you cannot help setting a background color on your UITableViewHeaderFooterView, and you do get that message in the console.

So what's the right answer to the question? There's no possible answer. Apple has made a huge goof here. They have provided a method that allows you to register a nib as the source of your UITableViewHeaderFooterView, but there is no UITableViewHeaderFooterView in the Object Library. Therefore this method is useless. It is impossible to design a UITableViewHeaderFooterView correctly in a nib.

This is a huge bug in Xcode. I filed a bug report on this matter in 2013 and it is still sitting there, open. I refile the bug year after year, and Apple keeps pushing back, saying "It has not been determined how or when the issue will be resolved." So they acknowledge the bug, but they do nothing about it.

What you can do, however, is design a normal UIView in the nib, and then, in code (in your implementation of viewForHeaderInSection), load the view manually from the nib and stuff it into the contentView of your header view.

For example, let's say we want to design our header in the nib, and we have a label in the header to which we want to connect an outlet lab. Then we need both a custom header class and a custom view class:

class MyHeaderView : UITableViewHeaderFooterView {
    weak var content : MyHeaderViewContent!
}
class MyHeaderViewContent : UIView {
    @IBOutlet weak var lab : UILabel!
}

We register our header view's class, not the nib:

self.tableView.register(MyHeaderView.self,
    forHeaderFooterViewReuseIdentifier: self.headerID)

In the view xib file, we declare our view to be a MyHeaderViewContent — not a MyHeaderView.

In viewForHeaderInSection, we pluck the view out of the nib, stuff it into the contentView of the header, and configure the reference to it:

override func tableView(_ tableView: UITableView, 
    viewForHeaderInSection section: Int) -> UIView? {
    let h = tableView.dequeueReusableHeaderFooterView(
        withIdentifier: self.headerID) as! MyHeaderView
    if h.content == nil {
        let v = UINib(nibName: "MyHeaderView", bundle: nil).instantiate
            (withOwner: nil, options: nil)[0] as! MyHeaderViewContent
        h.contentView.addSubview(v)
        v.translatesAutoresizingMaskIntoConstraints = false
        v.topAnchor.constraint(equalTo: h.contentView.topAnchor).isActive = true
        v.bottomAnchor.constraint(equalTo: h.contentView.bottomAnchor).isActive = true
        v.leadingAnchor.constraint(equalTo: h.contentView.leadingAnchor).isActive = true
        v.trailingAnchor.constraint(equalTo: h.contentView.trailingAnchor).isActive = true
        h.content = v
        // other initializations for all headers go here
    }
    h.content.lab.text = // whatever
    // other initializations for this header go here
    return h
}

It's dreadful and annoying, but it is the best you can do.

Solution 3

Create a UITableViewHeaderFooterView and its corresponding xib file.

class BeerListSectionHeader: UITableViewHeaderFooterView {
    @IBOutlet weak var sectionLabel: UILabel!
    @IBOutlet weak var abvLabel: UILabel!
}

Register the nib similarly to how you register a table view cell. The nib name and reuse identifier should match your file names. (The xib doesn't have a reuse id.)

func registerHeader {
    let nib = UINib(nibName: "BeerListSectionHeader", bundle: nil)
    tableView.register(nib, forHeaderFooterViewReuseIdentifier: "BeerListSectionHeader")
}

Dequeue and use similarly to a cell. The identifier is the file name.

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "BeerListSectionHeader") as! BeerListSectionHeader

    let sectionTitle = allStyles[section].name
    header.sectionLabel.text = sectionTitle
    header.dismissButton?.addTarget(self, action: #selector(dismissView), for: .touchUpInside)
    return header
}

Don't forget the header height.

 override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
     return BeerListSectionHeader.height
 }

Solution 4

I don't have enough reputation to add comment to Matt answer.

Anyway, the only thing missing here is to remove all subviews from UITableViewHeaderFooterView.contentView before adding new views. This will reset reused cell to initial state and avoid memory leak.

Share:
78,431

Related videos on Youtube

iamburak
Author by

iamburak

A developer who likes travelling the world, learning the most recent technologies and iOS development for about 5 years. Make the world a better place with your helpful entries for others. Greetings from Turkey.

Updated on July 09, 2022

Comments

  • iamburak
    iamburak almost 2 years

    I can create simple custom viewForHeaderInSection in programmatically like below. But I want to do much more complex things maybe connection with a different class and reach their properties like a tableView cell. Simply, I want to see what I do.

    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    
        if(section == 0) {
    
            let view = UIView() // The width will be the same as the cell, and the height should be set in tableView:heightForRowAtIndexPath:
            let label = UILabel()
            let button   = UIButton(type: UIButtonType.System)
    
            label.text="My Details"
            button.setTitle("Test Title", forState: .Normal)
            // button.addTarget(self, action: Selector("visibleRow:"), forControlEvents:.TouchUpInside)
    
            view.addSubview(label)
            view.addSubview(button)
    
            label.translatesAutoresizingMaskIntoConstraints = false
            button.translatesAutoresizingMaskIntoConstraints = false
    
            let views = ["label": label, "button": button, "view": view]
    
            let horizontallayoutContraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-10-[label]-60-[button]-10-|", options: .AlignAllCenterY, metrics: nil, views: views)
            view.addConstraints(horizontallayoutContraints)
    
            let verticalLayoutContraint = NSLayoutConstraint(item: label, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1, constant: 0)
            view.addConstraint(verticalLayoutContraint)
    
            return view
        }
    
        return nil
    }
    
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 50
    }
    

    Is there anyone to explain how can I create a custom tableView header view using xib? I have encountered with old Obj-C topics but I'm new with Swift language. If someone explain as detailed, It would be great.

    1.issue: Button @IBAction doesn't connect with my ViewController. (Fixed)

    Solved with File's Owner, ViewController base class (clicked left outline menu.)

    2.issue: Header height problem (Fixed)

    Solved adding headerView.clipsToBounds = true in viewForHeaderInSection: method.

    For constraint warnings this answer solved my problems:

    When I added ImageView even same height constraint with this method in viewController, it flow over tableView rows look like picture.

     func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 120
    }
    

    If I use, automaticallyAdjustsScrollViewInsets in viewDidLoad, In this case image flows under navigationBar. -fixed-

    self.automaticallyAdjustsScrollViewInsets = false
    

    3.issue: If button under View (Fixed)

    @IBAction func didTapButton(sender: AnyObject) {
        print("tapped")
    
        if let upView = sender.superview {
            if let headerView = upView?.superview as? CustomHeader {
                print("in section \(headerView.sectionNumber)")
            }
    
        }
    }
    
    • Curmudgeonlybumbly
      Curmudgeonlybumbly about 8 years
    • Rob
      Rob about 8 years
      FWIW, the accepted answer to that other question is a kludgy solution that was used before iOS offered dequeue capabilities for header/footer views.
  • iamburak
    iamburak about 8 years
    Appreciate your detailed answer, I have just started to follow your steps and approved as an answer. Later I can leave some comments here as small question. Thanks for all.
  • iamburak
    iamburak about 8 years
    I added all steps, header looks well. But I couldn't connect button with @IBAction in my ViewController. What I'm missing, Need I add another thing for my tableView?
  • Rob
    Rob about 8 years
    Did you set the File Owner of the NIB to be your view controller class? If so, when you select the button, the view controller should be one of the two classes that are available under the "Automatic" setting in the assistant editor.
  • iamburak
    iamburak about 8 years
    Ok, now I cannot handle section number, doesn't enter 'if let headerView = sender.superview as? CustomHeader {..' looks only 'tapped' on the xcode console screen. Also I have tried 'if let _ = buttonNIB.superview as? CustomHeader {' in CustomHeader subclass again, it didn' response.
  • Rob
    Rob about 8 years
    I'd suggest you examine your view hierarchy (eg using the view debugger) and just see what the button's superview is. Did you, for example, put the button within a container view of the CustomHeader?
  • iamburak
    iamburak about 8 years
    OK. When I drag my button to first hierarchy in CustomHeader, it works now. What if I have another button in the another view, how Can I reach parent CustomHeader to provide section number again?
  • iamburak
    iamburak about 8 years
    Alternatively I think that using headerView.goBtn.setTitle("sectionBtn", forState: .Normal) like this and then handle it in the subclass. But I doesn't give me section number.
  • iamburak
    iamburak about 8 years
    I understand, I need to two times different cast if my button in the another view, I have edited my question all problems encountered to be helpful everyone. Thanks again Rob.
  • Torsten B
    Torsten B almost 8 years
    I think it is worth mentioning: add 'self.tableView.sectionHeaderHeight = UITableViewAutomaticDimension' and 'self.tableView.estimatedSectionHeaderHeight = 70' to 'viewDidLoad'. If your constraints are pining each subview on all sides, you get Self-Sized headers
  • Thomás Pereira
    Thomás Pereira almost 8 years
    Thank you for detailed answer! ;)
  • djdance
    djdance about 7 years
    somehow NIB view bg color doesn't work, I have to set it in viewForHeaderInSection
  • Abhishek Mitra
    Abhishek Mitra almost 7 years
    Very Impressed and appreciate your answers, it helps me lot. Thanks
  • AnBisw
    AnBisw over 6 years
    Without you Mr @Rob I would be lost in this swift world :)
  • Jacob F. Davis C-CISO
    Jacob F. Davis C-CISO over 6 years
    To restate what @Rob said in an above comment, ensure that when you hook your IBOutlet to your xib that you select the name of the custom class, not File Owner.
  • J. Goce
    J. Goce about 6 years
    can I accomplish this without using NIB, I am doing my custom views programatically. how then can I register the custom UITableHeaderFooterView to my ViewController?
  • Rob
    Rob about 6 years
    @J.Goce - There's a form of register(_:forHeaderFooterViewReuseIdentifier:) that takes a class, rather than a NIB.
  • J. Goce
    J. Goce about 6 years
    @Rob thank you for pointing it out, I made the custom view header to be a subclass of UIView instead and return that custom view in viewForHeaderSection. works well also. Now my other problem is I need to update the custom header view of the other section when the current headerview is selected. Do you know how can I accomplish this?
  • Piotr
    Piotr about 6 years
    Why do you need MyHeaderView at all? Instead of subclassing UITableViewHeaderFooterView (which isn't recommended by Apple - "You can use this class as-is without subclassing in most cases.") you can register it directly - tableView.register(UITableViewHeaderFooterView.self, ...). Then if you want to access your MyHeaderViewContent you can use contentView as! MyHeaderViewContent.
  • Piotr
    Piotr about 6 years
    Great answer btw. Good job on trying to understand Apple's mess :)
  • matt
    matt about 6 years
    @Piotr “Then if you want to access your MyHeaderViewContent you can use contentView as! MyHeaderViewContent.” And crash? Why would that be good?
  • matt
    matt about 6 years
    Also “You can use this class as-is without subclassing in most cases.” is not a recommendation against subclassing. I subclass it just fine.
  • Bart van Kuik
    Bart van Kuik almost 6 years
    @matt, answer very much appreciated but one thing I don't understand. If I register a Nib in viewDidLoad(), and use dequeueReusableHeaderFooterView() later, then I very much get a UITableViewHeaderFooterView with a contentView. Of course, it's still not designable in Interface Builder so it still needs your solution.
  • The iCoder
    The iCoder almost 6 years
    If headerview == nil then its needs to NSBundle.mainBundle().loadNibNamed("Name", owner: nil, options: nil)[0]
  • Johan Karlsson
    Johan Karlsson over 5 years
    An easy to follow answer.
  • bitmusher
    bitmusher about 5 years
    Rather than use a UIView, you can make a prototype cell in your table, use dequeueReusableCell to get the UITableViewCell for it, then just copy the contentView from there into the backgroundView of your new UITableViewHeaderFooterView. If you plan to make changes to your view, then be aware that you might actually reuse that view object, but if your headers are purely visual then this works with no hitches. Don't forget to implement heightForHeaderInSection as well.
  • Awais Fayyaz
    Awais Fayyaz over 4 years
    Thanks. I used your technique but having a crash. Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSObject 0x600003b6eac0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key label.' Label is my outlet like yours is lab
  • matt
    matt over 4 years
    If you have a new question please ask a new question @AwaisFayyaz
  • Awais Fayyaz
    Awais Fayyaz over 4 years
    I don't have a new question. I was trying exactly the same thing and was trying to apply your technique by following the steps. The method pointed by Rob does not work as well. i am on xcode 10.2.
  • matt
    matt over 4 years
    @AwaisFayyaz You do have a new question. You have made a mistake. You are getting a “not key value coding compliant” error and you don’t understand it. I’m not going to explain it to you in these comments. It has nothing at all to do with my answer.
  • OhadM
    OhadM about 4 years
    @matt, thanks for the detailed explanation. A question, why not adding the nib directly to the UITableViewHeaderFooterView contentView property ? Why do we need to add another property (weak var content) ? Thanks.
  • RJ Smith
    RJ Smith over 3 years
    I couldn't change my background in the xib file, if anyone else has this issue, set the background of the "contentView" in the viewForHeaderInSection. For example: headerView.contentView.backgroundColor = UIColor.white
  • Rob
    Rob over 3 years
    You are correct, that setting the background color for the UITableViewHeaderFooterView in the NIB does not work, but you can set the background color for the contentView in the NIB, though. And if I did need to programmatically customize the background color, I'd personally do it in the UITableViewHeaderFooterView subclass, not in the UITableViewDelegate. See demo.