Search code examples
swiftxcodeuinavigationcontroller

UINavigation bar disappears when pressing back button


You can search for users in a tableview and it shows the back button in the UInavigation controller(pictured) When I tap on a row it takes me to the profile page from the tableView - however when I click back from the tableview the back button and UI navigation controller at the top disappears and you can only go back by swiping. Im not sure why this is happening.

The Tableview has a navigation controller embedded into a page view controller which holds the UIView controller.

Code 1 shows the tableview code 2 shows the profile page. Many thanks any help is appreciated.

import UIKit
import FirebaseFirestore
import Firebase

class ListOfUsersFromUniversity: UIViewController, UISearchBarDelegate {

    
    @IBOutlet weak var searchBar: UISearchBar!
    
    @IBOutlet weak var tableView: UITableView!
    
    
    var University:String = ""
    var users = [String]()
    var filteredUsers = [String]()
    var searching = false
          
  override func viewDidLoad() {
      super.viewDidLoad()
      tableView.delegate = self
      tableView.dataSource = self
      searchBar.delegate = self
      tableView.reloadData()
          }
         

              
    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        searchBar.becomeFirstResponder()
    }
    
      func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
          filteredUsers = users.filter({$0.lowercased().prefix(searchText.count) == searchText.lowercased()})
          searching = true
          tableView.reloadData()
      }
          
    
    override func viewWillAppear(_ animated: Bool) {
       self.navigationController?.navigationBar.isHidden = false
        let docRef = Firestore.firestore().collection("User-Universities").document(University)
        docRef.getDocument{ (document, error) in
          if let document = document {
          let data = document.data()
           let keydict = data!.keys
           let stringArray = Array(keydict)
           print(stringArray)
           for user in stringArray {
               service.getUsernameFromUID(user) { (username) in
                   self.users.append(username)
               }
           }
          } else {
            print("Document does not exist")
          }
        }
        DispatchQueue.main.async {
            self.tableView.reloadData()
        }
        
        searchBar.becomeFirstResponder()
    }
    
    
    override func viewWillDisappear(_ animated: Bool) {
        users.removeAll()
    }
        }
          


extension ListOfUsersFromUniversity: UITableViewDelegate, UITableViewDataSource  {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            if searching {
                return filteredUsers.count
                } else {
                return users.count
                }
            }
        
        
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
            if searching {
                cell.textLabel?.text = filteredUsers[indexPath.row]
            } else {
                cell.textLabel?.text = users[indexPath.row]
            }
            return cell
            
        }
        
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            let cell = tableView.cellForRow(at: indexPath)!
            let username = cell.textLabel!.text ?? ""
            let storyboard = UIStoryboard(name: "Search", bundle: nil)
      
            let newVC = storyboard.instantiateViewController(withIdentifier: "ProfilePage") as! ProfileViewController
            newVC.username = username
           // let navigationController = UINavigationController()
            self.navigationController?.pushViewController(newVC, animated: true)
            
            }
            

    }

import UIKit
import FirebaseFirestore
import Firebase
import Kingfisher

class ProfileViewController: UIViewController {

    let docRef = Firestore.firestore().collection("users")
    var username:String = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationController?.navigationBar.prefersLargeTitles = true
        self.title = username

        // Do any additional setup after loading the view.
    }
    
    override func viewWillAppear(_ animated: Bool) {
    self.navigationController?.navigationBar.isHidden = false
    }
    
}

extension ProfileViewController: UICollectionViewDataSource{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 12
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PostProfileCell", for: indexPath) as! PostCollectionCell
        cell.backgroundColor = .red
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        guard kind == UICollectionView.elementKindSectionHeader else {
        fatalError("Unexpected element kind.")
    }
    
        let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "ProfileHeader", for: indexPath) as! UserProfileHeaderCell
        
        docRef.whereField("username", isEqualTo: username)
            .getDocuments() { (querySnapshot, err) in
                if let err = err {
                    print("Error getting documents: \(err)")
                } else {
                    for document in querySnapshot!.documents {
                      let data = document.data()
                        let Link = data["ProfilePicUrl"] as? String ?? ""
                        let username = data["username"] as? String ?? ""
                        let university = data["University"] as? String ?? ""
                        let course = data["Course"] as? String ?? ""
                        let friends = data["friends"] as? Int
                        let url = URL(string: Link)
            DispatchQueue.main.async {
                headerView.University.text = university
                headerView.Course.text = course
                headerView.Friends.text = String(describing: friends!)
                headerView.profilePicture.layer.cornerRadius = headerView.profilePicture.frame.size.width/2
                headerView.profilePicture.clipsToBounds = true
                let placeholder = UIImage(systemName: "person.circle")
                headerView.profilePicture.kf.setImage(with: url, placeholder: placeholder)
                    }
                }
            }
        }
        
        
    return headerView
    }
    
    override func viewWillDisappear(_ animated: Bool) {
    self.navigationController?.navigationBar.isHidden = true
    }
    
}

extension ProfileViewController: UICollectionViewDelegateFlowLayout{
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let columns: CGFloat = 3
         let spacing: CGFloat = 1.5
         let totalHorizontalSpacing = (columns - 1) * spacing

         let itemWidth = (collectionView.bounds.width - totalHorizontalSpacing) / columns
         let itemSize = CGSize(width: itemWidth, height: itemWidth)

        return itemSize
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 1.5
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 1.5
    }
}


Solution

  • you could use viewWillAppear to set it to visible.

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(false, animated: true)
    }