ios - 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 ?? "")
}
}
解决方案
your view MenuOptionHeaderView
must inherit from UITableViewHeaderFooterView
or else this call :
optionsTableView.headerView(forSection: section) as! MenuOptionHeaderView
will not work and always returns nil.
推荐阅读
- python-3.x - 如何单击框以在页面底部显示更多行?
- dialogflow-es - 是否有可能以及如何使用对话流重定向到另一个网页?
- java - 如何在流中结合统计数据和映射器?
- r - 在 R-studio 中安装 arulesViz
- windows - Perl:在Windows中通过右键单击文件夹上的鼠标选择一个项目
- javascript - Vue,子组件说道具在视图更改时未定义
- ios - 检测手势并将其传递给模态视图控制器
- javascript - 使用我网站上的按钮运行 python 脚本
- php - 确定结合重叠范围的几个日期范围的“基数”
- python - Python:从 FuzzyWuzzy ExtractOne() 返回 Pandas DataFrame