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:
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
}

