首页 > 解决方案 > IOS swift tableview get headerview for a section

问题描述

Following is my code to add header to section

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let optionsForSection = isMutliLevelOptions() ? options : optionsList?[section]
    let sectionView = MenuOptionHeaderView()
    sectionView.isMultiSelectAllowed = allowsMultipleSelection(section)
    sectionView.selectedOptionsCount = getSelectedCount(section)
    sectionView.option = optionsForSection
    sectionView.setUI()
    //headerView = sectionView
    return sectionView
}

Following is code to access header of a section

  func updateHeader(section : Int) {
    let headerView : MenuOptionHeaderView = optionsTableView.headerView(forSection: section) as! MenuOptionHeaderView
    headerView.selectedOptionsCount = getSelectedCount(section)
    headerView.setUI()
}

But above code is crashing saying Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

Also I am getting warning Cast from 'UITableViewHeaderFooterView?' to unrelated type 'MenuOptionHeaderView' always fails at for my code

I am creating MenuOptionHeaderView using .xib file and is working fine I want to know how can I get header for a particular section

Following is code MenuOptionHeaderView

import UIKit

class MenuOptionHeaderView: UIView {

@IBOutlet weak var optionNameLbl: UILabel!


@IBOutlet weak var selectMinLbl: UILabel!



@IBOutlet var contentView: UIView!


var option : Options?
var selectedOptionsCount = 0
var isMultiSelectAllowed = false
override init(frame: CGRect) {
   super.init(frame: frame)
   commonInit()
}

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

func commonInit() {
   Bundle.main.loadNibNamed("MenuOptionHeaderView", owner: self, options: nil)
   contentView.fixInView(self)
}


func setUI() {


    optionNameLbl.text = isMultiSelectAllowed ?  "\(option?.name ?? "")(\(selectedOptionsCount))" :  (option?.name ?? "")


}


}

标签: iosswiftuitableviewtableviewnstableheaderview

解决方案


your view MenuOptionHeaderView must inherit from UITableViewHeaderFooterView or else this call :

optionsTableView.headerView(forSection: section) as! MenuOptionHeaderView

will not work and always returns nil.

Source : How to get section header from UItableView


推荐阅读