【发布时间】:2018-01-06 12:14:53
【问题描述】:
我有一个子类和扩展的表视图,然后在视图控制器中设置。我遇到的问题是委托方法 ViewForHeaderInSection 没有被调用,而普通数据源方法被调用。
(这是TableView的设置方法,在ViewDidLoad中调用。表格视图通过IBOutlet连接到View Controller)
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
}
}
这是视图控制器代码:
class ViewController: UIViewController {
@IBOutlet weak var myTableView: MyTableView!
override func viewDidLoad() {
super.viewDidLoad()
myTableView.setup()
}
}
委托方法没有被调用有什么具体原因吗?提前感谢您的宝贵时间。
【问题讨论】:
-
请检查我的回答。
标签: ios swift uitableview