Warm tip: This article is reproduced from serverfault.com, please click

How I can pin the tableHeaderView?

发布于 2020-12-01 14:31:17

Tell me, please, how I can pin the tableHeaderView on the ViewController's screen through code? I use this code, but the tableViewHeader disappears on scrolling:

import UIKit
class TestViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    lazy var tableViewTest = UITableView()
    override func viewDidLoad() {
        super.viewDidLoad()
        createTable()
    }
    private func createTable() {
        self.tableViewTest = UITableView(frame: view.bounds, style: .grouped)
        tableViewTest.register(TestTableViewCell.self, forCellReuseIdentifier: "Test") 
        self.tableViewTest.delegate = self
        self.tableViewTest.dataSource = self
        tableViewTest.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        tableViewTest.separatorInset.left = 10
        tableViewTest.separatorInset.right = 10
        tableViewTest.tableHeaderView = "Test Header"
        view.addSubview(tableViewTest)
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Test", for: indexPath) as! TestTableViewCell
        cell.testLabel.text = "test label"
        return cell
     }
}

This is my second class:

import UIKit
class TestTableViewCell: UITableViewCell {
   let testLabel = UILabel()
   override func layoutSubviews() {
       super.layoutSubviews()
       testLabel.frame = CGRect(x: 60, y: 5, width: UIScreen.main.bounds.width - 80, height: 50)
            testLabel.numberOfLines = 0
            testLabel.sizeToFit()
            addSubview(testLabel)
       }
   override func awakeFromNib() {
        super.awakeFromNib()
   }
   override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
   }
}
Questioner
Мария G
Viewed
0
Dmitry Kuleshov 2020-12-01 23:43:53

Try to use the implicit construct of UITableView

lazy var tableViewTest = UITableView(frame: .zero, style: .plain)

But also you need to change your table header to section header which you can define in UITableViewDelegate method

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let identifier = YourSectionHeaderView.reuseIdentifier
        let headerView =
            tableView.dequeueReusableHeaderFooterView(withIdentifier: identifier) 
        return headerView
    }

By the way, I also recommend you to use constraint instead of autoresizing mask