3

I have a table in which I need to add a title view. I made it in an xib file to configure as I need, but I have problems connecting this view. Tell me what I'm doing wrong!

class HeaderTableView: UITableViewHeaderFooterView {
//I think in this class a mistake

    override init(reuseIdentifier: String?) {
        super.init(reuseIdentifier: reuseIdentifier)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}




 override func viewDidLoad() {
        super.viewDidLoad()

         let nib = UINib(nibName: "HeaderTableView", bundle: nil)
        tableView.register(nib, forHeaderFooterViewReuseIdentifier: "HeaderTableView")
    }


    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
            let view = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: "HeaderTableView")  as! HeaderTableView

            returnview
        }
JiosDev
  • 324
  • 3
  • 11

3 Answers3

10

So you mentioned you added your Header view in a xib file, as you wanted to design it freely from the Interface Builder.

First thing go to your XIB based Header View (HeaderTableView.xib), in Identity Inspector and put there the class name of your Header View as of HeaderTableView:

Second thing, open your HeaderTableView swift class (in my example this is within ViewController.swift file). To open it in parallel with your already open XIB based file (keep ALT/OPTION key pressed while you click on the swift file containing that class) and link your IBOutlet from InterfaceBuilder to the Swift code like this:

Third, your implementation (for HeaderTableView class) looks good on the swift file, but small adjustments in the HeaderTableView class are needed to make it work from InterfaceBuilder, just to give you an example what I did in my machine to make a simple sample I have this two classes for the TableView UIViewController and the HeaderTableView class (both within ViewController.swift file but you can separate them in two files if needed):

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let nib = UINib(nibName: "HeaderTableView", bundle: nil)
        tableView.register(nib, forHeaderFooterViewReuseIdentifier: "HeaderTableView")
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        10
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: "HeaderTableView")  as! HeaderTableView

        return view
    }
}

class HeaderTableView: UITableViewHeaderFooterView {
    @IBOutlet weak var titleLabel: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()

        titleLabel.text = "Title"
    }

    override init(reuseIdentifier: String?) {
        super.init(reuseIdentifier: reuseIdentifier)
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
}

And as a result I have this:

Don't forget in your ViewController InterfaceBuilder to make the tableView as delegate and dataSource (my UIViewController in InterfaceBuilder is within Main.storyboard for example):

1)

2)

denis_lor
  • 6,212
  • 4
  • 31
  • 55
  • thanks but i get an error in the method `viewForHeaderInSection`. This `Cast from UITableViewHeaderFooterView? to unrelated type HeaderTableView always fails` in a row `let view = self.tableView ....` – JiosDev Mar 16 '20 at 09:43
  • If you follow step by step my indications you should be able to build a working sample as I did to show you the screenshot. Take a look better maybe you missed something! – denis_lor Mar 16 '20 at 09:52
3

So as per your comment if you want to add Table header then you should not use XIB because you can achieve the same thing using storyboard. Its easy and better way to do it. Just drag and drop UIView to scene dock of your view controller and take the outlet of that view and assign that view to tableheader like this.

table.tableHeaderView = yourview

enter image description here

I used it as a tablefooterview.

You can adjust the height of that view from size inspector.

CrackIt
  • 606
  • 1
  • 5
  • 15
1

Good day, Table view has 5 parts, the first part is the tableHeaderView , SectionHeader , Cell, SectionFooter , and final tableFooterView.

If you want to add title on the top of the tableview you can use this code.

class HeaderTableView : UIView{

    var title : UILabel = {
        let label = UILabel()
        label.text = "My Title"
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupLabel()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func setupLabel(){
        addSubview(title)
        NSLayoutConstraint.activate([
            title.centerYAnchor.constraint(equalTo: self.centerYAnchor),
            title.centerXAnchor.constraint(equalTo: self.centerXAnchor),
        ])
    }


}

class ViewController: UITableViewController {


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        var tableHeaderView = HeaderTableView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 200))
        tableHeaderView.backgroundColor = .red
        tableView.tableHeaderView = tableHeaderView
    }



}

enter image description here

cristian_064
  • 576
  • 3
  • 16
  • 1
    Your answer is good, but you create a view (give it the size and color of the background) And I already have a view and need to connect it to the place of your red view – JiosDev Mar 16 '20 at 09:45
  • you can create the Views by code or by .xib, anyway I recommended use tableheaderview for add title to tableView instead section Header, because the you can have several HeaderSection in one tableView. – cristian_064 Mar 16 '20 at 14:11