'iOS: App freezes when start typing in UISearchBar

I have a UICollectionViewController and I show the search bar when the user taps on a button. But when the user start typing in the search field the app freezes and the memory starts skyrocking on this line

self.collectionView?.reloadData()

This is happening ONLY in iOS 15+. All version before that are working like a charm.

Here is my code:

//Create search bar

lazy var searchBar: UISearchBar = {
    let sb = UISearchBar()
    sb.placeholder = "Enter search text"
    sb.barTintColor = .darkGray
    sb.tintColor = .darkGray
    UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).backgroundColor = .white
    UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).textColor = .darkGray
    sb.delegate = self
    return sb
}()

When the user taps on a button I add it to the navigation bar

   fileprivate func addSearchBar() {
        navigationController?.navigationBar.addSubview(searchBar)
        searchBar.anchor(top: navigationController?.navigationBar.topAnchor, left: navigationController?.navigationBar.leftAnchor, bottom: navigationController?.navigationBar.bottomAnchor, right: navigationController?.navigationBar.rightAnchor, paddingTop: 4, paddingLeft: 64, paddingBottom: 4, paddingRight: 64, width: 0, height: 0, centerX: navigationController?.navigationBar.centerXAnchor, centerY: navigationController?.navigationBar.centerYAnchor)
        navigationItem.title = ""
        searchBar.becomeFirstResponder()
    }

And when the user start typing the searchBar func is called

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        if searchText.isEmpty {
            filteredItems = items
        } else {
            filteredItems = self.items.filter { (item) -> Bool in
                let name = items.name?.lowercased()
                let search = searchText.lowercased()
                return ((name?.contains(search))!)
            }
            if filteredItems.count == 0 {
                emptyCellTitle = "No items found."
            }
        }

        self.collectionView?.reloadData() // the freeze happens here

    }

When the

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String)

is removed there is no freeze and the user can type what he wants without problems but the data is not filtered.

Currently I'm out of options. I have tried every solution I found but nothing is working. Any suggestion will be highly appreciated!

Again, this is happening ONLY in iOS 15 and up. Thanks!



Sources

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

Source: Stack Overflow

Solution Source