Reputation: 1679
I created a custom header view for a UITableView
. The type of the header view is UITableViewCell
. I implemented it in the storyboard and added it to the view hierarchy like its shown in the screenshot below
Here is my Code for UITableViewController
import UIKit
class SecondCustomTableViewController: UITableViewController {
@IBOutlet weak var customHeaderView: UITableViewCell!
let array = ["Row 1", "Row 2", "Row 3"]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(SecondCustomTableViewController.self, forHeaderFooterViewReuseIdentifier: "Header")
self.tableView.dequeueReusableHeaderFooterView(withIdentifier: "Header")
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = "\(array[indexPath.row])"
return cell
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 44
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
print("\(customHeaderView) -> Section: \(section)")
return customHeaderView
}
}
When i run it in the simulator it looks like this
My question is: Why is my custom header view shown for the last section only?
The print statement in the viewForHeaderInSection
method looks like this:
Optional(<UITableViewCell: 0x7ff287802200; frame = (0 0; 375 44); clipsToBounds = YES; layer = <CALayer: 0x600000038d00>>) -> Section: 0
Optional(<UITableViewCell: 0x7ff287802200; frame = (0 0; 375 44); clipsToBounds = YES; autoresize = W; layer = <CALayer: 0x600000038d00>>) -> Section: 1
Optional(<UITableViewCell: 0x7ff287802200; frame = (0 176; 375 44); clipsToBounds = YES; autoresize = W; layer = <CALayer: 0x600000038d00>>) -> Section: 2
I also unwrapped the optional to make it a non optional but its the same behavior. As the print statement shows the viewForHeaderInSection
method is called three times, so why the header shows up for the last section only?
I hope someone can help me with this. Every hint is highly appreciated.
Upvotes: 0
Views: 115
Reputation: 374
I think its because ui elements cannot be copied, what you are doing is make an instance of UITableViewCell as IBOutlet. Better you can create your view when it needs.
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return tableView.dequeueReusableCell(withIdentifier: "Header") as! UITableViewHeaderFooterView
}
Hope it helps. Sorry for my bad english.
Upvotes: 2