Search code examples
iosswiftxcodeuitableviewtableview

Fixed Height for Navigation bar on UITableView scroll


Problem:

I would like the navigation bar and large title to remain fixed when scrolling the tableView. How can I set it programmatically so that when the tableView is scrolled the navigation bar does not drag up/down or hide the large title?

Code:

override func loadView() {
        super.loadView()
        
        setupTableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorInset = .zero
        tableView.layoutMargins = .zero
        self.tableView.layoutMargins = UIEdgeInsets(top: 0,left: 0,bottom: 0,right: 0)
        self.tableView.contentInset = UIEdgeInsets(top: 0,left: 0,bottom: 0,right: 0)
     
    }
    
    func setupTableView() {
        view.addSubview(tableView)
        tableView.separatorColor = .label
        tableView.layer.shadowColor = UIColor.black.cgColor
        tableView.layer.shadowOffset = CGSize(width: 0, height: 0)
        tableView.backgroundColor = .systemBackground
        tableView.tableFooterView = UIView()
        tableView.isScrollEnabled = true
        //tableView.bounces = false
        tableView.showsVerticalScrollIndicator = true
        tableView.clipsToBounds = true
        let nib = UINib(nibName: "ChatTableViewCell", bundle: nil)
       tableView.register(nib, forCellReuseIdentifier: "ChatTableViewCell")
   
    }

func configNavBar() {
        
        navigationController?.navigationBar.barTintColor = .black
        navigationController?.navigationBar.backgroundColor = .black
        self.navigationController?.navigationBar.backgroundColor = .black
        
        self.title = "Bitcoin"
     
        let navBarAppearance = UINavigationBarAppearance()
        //navBarAppearance.configureWithOpaqueBackground()
        navBarAppearance.shadowColor = .clear
        navBarAppearance.shadowImage = UIImage()
        navBarAppearance.backgroundColor = .black
        navBarAppearance.largeTitleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
        
        navigationController?.navigationBar.standardAppearance = navBarAppearance
        navigationController?.navigationBar.scrollEdgeAppearance = navBarAppearance

        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Log out", style: .done, target: self, action: #selector(didTapLogout))
        self.navigationItem.rightBarButtonItem?.tintColor = .systemGray  
    }

I am programmatically setting the table view like so. I would like the navigation bar to remain static when the table view is scrolled.


Solution

  • I solve it with this simple line, I don't know why ( I tried searching but couldn't find anything that justifies it ) but if you add a blank UIView in your view, the navigation bar remain static. Add below line in viewDidLoad:

    view.addSubview(UIView())