1

I know that this is somewhat a common question, but I am trying to call the textDidChange function in my searchBar delegate. I am able to call the updateSearchResults func, but for some reason I am not able to call textDidChange (the print statement does not show when printing within the textDidChange func). As an end goal I am trying to filter my collectionView based on search text inputs - "A" text in the searchBar will return only users with the first letter "A" in their "name" dictionary value. I am able to load all users in the SearchPeopleResultsVC when user enters some text in the searchPeople searchBar, but nothing happens when a letter is entered in the searchbar.

The kicker is I have a "menuBar" collectionView class where each cell delegates to another collectionView. The one I am having problems with is the searchPeopleController (indexPath 1). See screenshots and code below. Thanks in advance!

enter image description here enter image description here

// data model class

class CurrentTraveler: SafeJsonObject {
    var name: String?
    var profileImageUrl: String?
    var travelingPlace: String?

    init(dictionary: [String: AnyObject]) {
        super.init()

        self.name = dictionary["name"] as? String
        self.profileImageUrl = dictionary["profileImageUrl"] as? String
        self.travelingPlace = dictionary["users/uid/Places"] as? String
        setValuesForKeys(dictionary)
    }
}

// searchVC class that holds the menuBar collectionView

class SearchVC: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UISearchControllerDelegate, UISearchBarDelegate {

    var users = [CurrentTraveler]()
    var isSearching = false
    var filteredData = [CurrentTraveler]()
    var peopleResultsViewController: SearchPeopleResultsVC?   
    var searchPeopleTableView: SearchPeopleCollectionView?
    var filtered:[String] = []
    var searchActive : Bool = false
    var searchPeopleController: UISearchController?

    let cellId1 = "cellId1"
    let cellId2 = "cellId2"

    lazy var contentCollectionView: UICollectionView = {
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        return cv
    }()

    override func viewDidLoad() {
        super.viewDidLoad()  

        peopleResultsViewController?.collectionView.delegate = self
        peopleResultsViewController?.collectionView.dataSource = self
        searchPeopleController?.searchBar.delegate = self
    }

    func scrollToMenuIndex(menuIndex: Int) {
        let indexPath = IndexPath(item: menuIndex, section: 0)
        contentCollectionView.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition(), animated: true)

        if indexPath.item == 1 {
            searchPeopleController?.delegate = self
            searchPeopleController?.searchBar.delegate = self
            peopleResultsViewController = SearchPeopleResultsVC()
            searchPeopleController = UISearchController(searchResultsController: peopleResultsViewController)
            searchPeopleController?.searchResultsUpdater = peopleResultsViewController
            searchPeopleController?.searchBar.resignFirstResponder()

            navigationItem.titleView = searchPeopleController?.searchBar
            definesPresentationContext = true
        }

        if indexPath.item == 0 {
            // sets up place collectionview...
        }
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId1", for: indexPath) 
        if indexPath.item == 0 {
            // return first collectionView for places...
        }

        if indexPath.item == 1 {
            let usersCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId2", for: indexPath) as! SearchPeopleCollectionView
            usersCell.searchVC = self
            return usersCell
        }
        return cell
    }
}

// searchResultsVC for People collectionView searchbar

class SearchPeopleResultsVC : UIViewController, UISearchResultsUpdating, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UISearchBarDelegate {

    let cellId = "cellId"

    var users = [CurrentTraveler]()
    var filteredData = [CurrentTraveler]()
    var isSearching = false
    var searchVC: SearchVC?
    var peopleResultsViewController: SearchPeopleResultsVC?

    var filtered:[String] = []
    var searchActive : Bool = false
    let searchPeopleController = UISearchController(searchResultsController: nil)

    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.dataSource = self
        cv.delegate = self
        return cv
    }()

    override func viewDidLoad() {
        collectionView.delegate = self
        collectionView.dataSource = self

        searchPeopleController.searchBar.delegate = self

        fetchTravelingUserCell()
    }

    func fetchTravelingUserCell() {
        Database.database().reference().child("users").observe(.childAdded, with: { (snapshot) in
            if let dictionary = snapshot.value as? [String: AnyObject] {
                let user = CurrentTraveler(dictionary: dictionary)
                self.users.append(user)
                DispatchQueue.main.async(execute: {
                    self.collectionView.reloadData()
                })
            }
        }, withCancel: nil)
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if searchPeopleController.isActive && searchPeopleController.searchBar.text != "" {
            return users.count
        }
        return filteredData.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as? BaseGlobalSearchUser else { fatalError("Expected to display a `DataItemCollectionViewCell`.") }

        if searchPeopleController.isActive && searchPeopleController.searchBar.text != "" {
            cell.currentTraveler = filteredData[indexPath.item]
        } else {
            cell.currentTraveler = users[indexPath.item]
        }
        return cell
    }

    var filterString = "" {
        didSet {
            guard filterString != oldValue else { return }

            if filterString.isEmpty {
                filteredData = users
            }
            else {
                filteredData = users.filter { ($0.name?.localizedStandardContains(filterString))! }
            }
            self.collectionView.reloadData()
        }
    }

    func updateSearchResults(for searchPeopleController: UISearchController) {
        filterString = searchPeopleController.searchBar.text ?? ""
        filteredData = users
        filteredData = users.filter({$0.name?.range(of: filterString) != nil})
        self.collectionView.reloadData()

    }

    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        searchActive = true
    }

    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        searchActive = false
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        searchActive = false
    }

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchActive = false
    }

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        filterString = searchPeopleController.searchBar.text ?? ""
        print(filterString)
    }
}
user3708224
  • 1,229
  • 4
  • 19
  • 37
  • Please check https://stackoverflow.com/questions/29109943/search-bar-not-calling-textdidchange-for-some-reason – Vini App Sep 20 '17 at 04:46

0 Answers0