Search code examples
swiftuitableviewxib

UItableView Section Header View with Xib Error - Swift


I try to implement Section Header with Xib File. I create a Xib View and attend UITableViewHeaderFooterView to this view . When I run the App , it gives me error without any description. Where is the problem ?

Thanks in advance.

tableView.register(UINib(nibName: "EventViewCell", bundle: nil), forCellReuseIdentifier: "EventViewCell")
tableView.register(UINib(nibName: "EventCellSectionHeader", bundle: nil), forHeaderFooterViewReuseIdentifier: "EventCellSectionHeader")


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

    let cell = tableView.dequeueReusableHeaderFooterView(withIdentifier: "EventCellSectionHeader") as! EventCellSectionHeader
    cell.headerName.text = "aa"
    return cell
}

class EventCellSectionHeader: UITableViewHeaderFooterView {
    @IBOutlet var headerName: UILabel!  
}

libc++abi.dylib: terminating with uncaught exception of type NSException


Solution

  • Xcode 10 SWIFT 4

    implement your viewForHeaderInSection as below:

    //EventCellHeader is the name of your xib file. (EventCellHeader.xib)
        func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    
            let header = Bundle.main.loadNibNamed("EventCellHeader", owner: self, options: nil)?.last as! EventCellSectionHeader
            header.headerName.text = "aa"
    
            return header
    
        }
    

    I tested it: (if you need more help let me know to send you the whole project)

    enter image description here