Use Header In Section [TableViewCell] Swift 4


source: screen shot use header


   The viewForHeaderInSection method belongs to the UITableViewDelegate Protocol. You therefore must set the delegate of your table view to your view controller in order to get this callback. You probably did just set the tableview's dataSource as your other methods are called.

and this example full code without xib file. :)

import UIKit

class HeaderTableViewController: UITableViewController {

    let sectionNames = [ "iPhone", "iPad", "Apple Watch", "Apple Watch" ]
     let sectionItems = [["iPhone 5", "iPhone 5s", "iPhone 6", "iPhone 6 Plus", "iPhone 7", "iPhone 7 Plus"],
    ["iPad Mini", "iPad Air 2", "iPad Pro", "iPad Pro 9.7"],
    ["Apple Watch", "Apple Watch 2", "Apple Watch 2 (Nike)"]]

    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title = "Apple Product"
        navigationController?.navigationBar.prefersLargeTitles = true
        tableView.register(UINib(nibName: "ApiTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")

    }
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return self.sectionItems.count
    }
    
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? ApiTableViewCell
        cell?.merkLabel.text = self.sectionNames[section]
        return cell
    }
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 34
    }
    
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.sectionItems[section].name.count
        
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ApiTableViewCell
        let name = self.sectionItems[indexPath.section].name[indexPath.row]
        cell.merkLabel.text = name
        
        return cell
    }

}


No comments: