'Searchbar doesn't disappear while scrolling in Swift

I work with Xcode 13.4. I have a searchBar and I want it disappear while scrolling. I use this but it doesn't work.

navigationItem.hidesSearchBarWhenScrolling = true

Here is my all code.

import UIKit


class WordsVC: UIViewController, UISearchResultsUpdating, UISearchBarDelegate {


    
let searchController = UISearchController()


let tableView : UITableView = {
    let tableView = UITableView()
    tableView.register(WordsTableListViewCell.self, forCellReuseIdentifier: WordsTableListViewCell.identifier)
    tableView.register(AddRowTableViewCell.self, forCellReuseIdentifier: AddRowTableViewCell.identifier)
    return tableView
}()



override func viewDidLoad() {
    super.viewDidLoad()
    
    view.addSubview(tableView)
    
    initSearchController()
    
    
   
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    
    tableView.delegate = self
    tableView.dataSource = self
   
        
}


func initSearchController(){
    
    searchController.loadViewIfNeeded()
    searchController.searchResultsUpdater = self
    searchController.obscuresBackgroundDuringPresentation = false
    searchController.searchBar.enablesReturnKeyAutomatically = false
    searchController.searchBar.returnKeyType = UIReturnKeyType.done
    definesPresentationContext = false
    
    navigationItem.searchController = searchController
    navigationItem.hidesSearchBarWhenScrolling = true
    searchController.searchBar.delegate = self
    
    
}

}

I deleted some unnecessary parts on my code. But as a summary, I have a tableView and added it programmetically.

I couldn't find the problem. This is my second project that containing searchBar and I suppose that I didn't change anything.

Can you see the problem on my code? I searched on the internet. There are some people who encounter with same problem but I could not find any proper solution.

Thanks in advance.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source