Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I am trying to set height for header and footer in section through code but it doesn't work

I tried to set height for footer and header for section in table view through code but it doesn’t work . When I do it from storyboard , it works fine .

This is my code

import UIKit

class MyTableViewController: UIViewController {

    @IBOutlet weak var myTable : UITableView!
    
    let spacing : CGFloat = 20
    
    override func viewDidLoad() {
        super.viewDidLoad()
        myTable.delegate = self
        myTable.dataSource = self
    }
}

extension MyTableViewController : UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = myTable.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = "Random text"
        cell.accessoryType = .detailButton
        return cell
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 5
    }

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

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return spacing
    }
}

Output of the code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Output of the code

I want to have some padding to the cells

>Solution :

By default, UITableViewDelegate will return nil in viewForHeaderInSection (the same as with the footer) if you aren’t conforming. In the storyboard, you can directly drag a cell or view, it represents dynamic prototypes, that’s why it works until you add table’s Delegate/DataSource.

Add this delegate method:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let view = UIView()
    view.backgroundColor = .red
    //... some configurations here if needed
    return view
}

func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    let view = UIView()
    view.backgroundColor = .orange
    //... some configurations here if needed
    return view
}

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading