How to filter UICollectionView and keep keyboard up?

前端 未结 11 1550
旧时难觅i
旧时难觅i 2020-12-30 23:47

I\'ve added a UISearchBar to a UICollectionView and in the delegate searchBar:textDidChange: filter my model and call [collectio

11条回答
  •  离开以前
    2020-12-31 00:52

    I faced this issue when dealing with UITextFields inside an UICollectionViewCell. I think search bar may follow the same path.

    I have a bunch of collection view cells which populate from;

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    
        let question = questions[indexPath.row]
        let cell: QuestionBaseCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: cellName, for: indexPath) as! QuestionBaseCollectionViewCell
        cell.arrangeCell(question: question) // Here cell populates from server data 
        cell.delegate = self
        return cell
    }
    

    This QuestionBaseCollectionViewCell has a delegate method, which updates the answer of the question to its delegate. I need to update the server side data.

    In the delegate method; If I put reloadData method the textfield resigns and keyboard is disappearing.

    Also I do not have direct access to the UITextField which yields to I cannot use cell.textField.becomeFirstResponder() etc.

    So, I comment out the reloadData() method.

    func questionCollectionViewCell(_ cell: QuestionBaseCollectionViewCell, didChange choice: Choice) {
        guard let indexPath = collectionView.indexPath(for: cell) else { return }
        var question = questions[indexPath.row]
        guard let choiceIndex = question.choices?.firstIndex(where: { $0.id == choice.id }) else { return }
        question.choices?[choiceIndex] = choice
        questions[indexPath.row] = question
    
        // collectionView.reloadData()
    }
    

    Here is what I did;
    I made call to reloadData() after keyboard dismiss. See below.

    Just add a keyboardDidHideNotification to the corresponding view controller in viewWillAppear method (note: you may put wherever you want depends on your needs) as follows:

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(handleKeyboardDidHide(_ :)),
                                               name: UIResponder.keyboardDidHideNotification,
                                               object: nil)
    }
    

    and the observer method;

    @objc func handleKeyboardDidHide(_ notification: Notification) {
        collectionView.reloadData()
    }
    

    That's it. After the keyboard will hide, you may save your data.

    Hope it helps!

提交回复
热议问题