1

image 1 this is the initial estimated behaviour. image 2 after searchbar became active this is the behaviour. image 3 once after changing the orientation to landscape, keyboard dismissed along with that search bar gets defocused and even after tapping cancel, Cancel button is not hiding.

class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating {
    // Table view and search controller
    private var tableView: UITableView!
    private var searchController: UISearchController!
    
    // Data source
    private var data: [String] = ["Apple", "Banana", "Orange", "Pineapple", "Grapes", "Watermelon"]
    private var filteredData: [String] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "My View Controller"
        view.backgroundColor = .systemBackground
        // Set up table view
        tableView = UITableView()
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.dataSource = self
        tableView.delegate = self
        view.addSubview(tableView)
        
        NSLayoutConstraint.activate([
            tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            tableView.topAnchor.constraint(equalTo: view.topAnchor),
            tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        ])
        
        // Set up search controller
        searchController = UISearchController(searchResultsController: nil)
        searchController.searchResultsUpdater = self
        searchController.obscuresBackgroundDuringPresentation = false
        navigationItem.searchController = searchController
        navigationItem.hidesSearchBarWhenScrolling = false
        navigationItem.largeTitleDisplayMode = .always
        navigationController?.navigationBar.prefersLargeTitles = true
        definesPresentationContext = true
    }
    
    // MARK: - Table View DataSource
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if isFiltering() {
            return filteredData.count
        } else {
            return data.count
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
        let item: String
        
        if isFiltering() {
            item = filteredData[indexPath.row]
        } else {
            item = data[indexPath.row]
        }
        
        cell.textLabel?.text = item
        
        return cell
    }
    
    // MARK: - Table View Delegate
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        // Handle row selection if needed
    }
    
    // MARK: - Search Controller
    
    func updateSearchResults(for searchController: UISearchController) {
        let searchText = searchController.searchBar.text ?? ""
        filterContent(for: searchText)
    }
    
    func filterContent(for searchText: String) {
        filteredData = data.filter { item in
            return item.lowercased().contains(searchText.lowercased())
        }
        
        tableView.reloadData()
    }
    
    func isFiltering() -> Bool {
        return searchController.isActive && !searchBarIsEmpty()
    }
    
    func searchBarIsEmpty() -> Bool {
        return searchController.searchBar.text?.isEmpty ?? true
    }
}

this sample implementation is absolute working fine in regular devices.

  • What do you mean by "regular" devices and "compact" devices? – HangarRash Jul 03 '23 at 17:13
  • Size classes are traits assigned to a user interface element, such as a screen or a view. There are two types of size classes in iOS 8: regular and compact. A regular size class denotes either a large amount of screen space, such as on an iPad, or a commonly adopted paradigm that provides the illusion of a large amount of screen space, such as scrolling on an iPhone. Every device is defined by a size class, both vertically and horizontally. Please refer this [link](https://stackoverflow.com/questions/25693318/difference-between-compact-and-regular-size-class), you will get in detail. – Balaji Royal Jul 05 '23 at 05:26
  • i know what size classes are. I've just never seen anyone use the term "regular devices" and "compact devices". What do you mean by that? An iPhone, for example, normally has regular height in portrait and compact width in portrait. So it makes no sense to refer to a device as being "regular" or "compact". "Regular" and "compact" are associated with the width and height and depend on device orientation. Or on an iPad, whether split screen is in use or not. So no, no device is defined by size class. – HangarRash Jul 05 '23 at 05:40

1 Answers1

0

Add it the search controller property:

class MyTableViewController: UTableViewController, UISearchResultsUpdating {
let searchController = UISearchController(searchResultsController: nil) }

Add the search bar in viewDidLoad:

override func viewDidLoad() {
super.viewDidLoad()

searchController.searchResultsUpdater = self
searchController.hidesNavigationBarDuringPresentation = false
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.sizeToFit()
self.tableView.tableHeaderView = searchController.searchBar }

and check this answer, hopefully it will solve your problem

How to implement UISearchController in UITableView - Swift

Chandaboy
  • 1,302
  • 5
  • 10