[英]UITableView delegate method not being called in swift 3
我有一个被继承和扩展的表视图,然后在视图控制器中进行设置。 我遇到的问题是未调用委托方法ViewForHeaderInSection,而正在调用普通的数据源方法。
(这是TableView设置方法,在ViewDidLoad中调用。表视图通过IBOutlet连接到视图控制器)
func setup() {
self.dataSource = self as UITableViewDataSource
self.delegate = self
let nib = UINib(nibName: "MyTableViewCell", bundle: nil)
self.register(nib, forCellReuseIdentifier: "MyCell")
}
这些是扩展
extension MyTableView: UITableViewDataSource,UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
//print(Genres.total.rawValue)
return Genres.total.rawValue
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let tableSection = Genres(rawValue: section), let articleData = articleDictionary[tableSection] {
// print(articleData.count)
return articleData.count
}
print(0)
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell") as! MyTableViewCell
if let tableSection = Genres(rawValue: indexPath.section), let article = articleDictionary[tableSection]?[indexPath.row]{
cell.cellTitle.text = article.articleTitle
cell.cellImageView.image = article.articleImage
cell.cellEmojiReaction.text = article.articleEmojis
}
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: 40.0))
view.backgroundColor = .brown
let label = UILabel(frame: CGRect(x: 16, y: 0, width: tableView.bounds.width, height: 40))
label.textColor = .blue
let tableSection = Genres(rawValue: section)
switch tableSection {
case .breakingNews?:
label.text = "Breaking News"
case .scienceAndTech?:
label.text = "Science and Tech"
case .entertainment?:
label.text = "Entertainment"
case .sports?:
label.text = "Sports"
default:
label.text = "Invalid"
}
print("Function Run")
view.addSubview(label)
print(label.text ?? "Nothing Here")
return view
}
}
这是View控制器代码:
class ViewController: UIViewController {
@IBOutlet weak var myTableView: MyTableView!
override func viewDidLoad() {
super.viewDidLoad()
myTableView.setup()
}
}
为什么没有调用委托方法的任何特定原因? 预先感谢您的宝贵时间。
为此,您还必须实现一个另外的方法heightForHeaderInSection
和viewForHeaderInSection
方法。
如果您使用的是viewForHeaderInSection委托方法,则必须使用heightForHeaderInSection方法,否则不会调用其他明智的节标题方法
在iOS 5.0之前,对于tableView(_:viewForHeaderInSection :)返回nil视图的部分,表视图会自动将标头的高度调整为0。 在iOS 5.0和更高版本中,您必须使用此方法返回每个节标题的实际高度。
官方链接以获取更多描述https://developer.apple.com/documentation/uikit/uitableviewdelegate/1614855-tableview
在viewDidLoad中添加:
tableView.estimatedSectionHeaderHeight = 80
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.