Making a textView in a collectionView cell the fir

2019-08-20 16:54发布

I have a collectionView and allow a user to dynamically add cells to the collectionView. The view controller only shows one cell at a time and I want the first textView (which is part of the cell) to become the firstResponder (and keep the keyboard visible at all times), which works fine when loading the view controller (as well as in one of the cases below).

I have created a method to detect the current cell, which I call every time in any of these cases: (1) user scrolls from one cell to another (method placed in scrollViewWillEndDragging), (2) user taps UIButtons to navigate from one cell to another, (3) user taps UIButton to create and append a new cell at the end of the array (which is used by the collectionView).

This is the method:

func setNewFirstResponder() {
    let currentIndex = IndexPath(item: currentCardIndex, section: 0)
    if let newCell = collectionView.cellForItem(at: currentIndex) as? AddCardCell {
        newCell.questionTextView.becomeFirstResponder()
    }
}

Now my problem is that this only works in case (1). Apparently I have no cell of type AddCardCell in cases (2) and (3). When I print the currentCardIndex, I get the same result, in all of the cases, which is very confusing.

Any hints why I wouldn't be able to get the cell yet in cases 2 and 3, but I am in case 1?

As a reference here are some of the methods that I am using:

//Update index and labels based on user swiping through card cells
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    //Update index based on targetContentOffset
    let x = targetContentOffset.pointee.x
    currentCardIndex = Int(x / view.frame.width)

    setNewFirstResponder()
}

And the other method, from which it doesn't work (case 3):

//Method to add a new cell at end of collectionView
@objc func handleAddCell() {
    //Inserting a new index path into tableView
    let newIndexPath = IndexPath(item: autoSaveCards.count - 1, section: 0)
    collectionView.insertItems(at: [newIndexPath])

    collectionView.scrollToItem(at: newIndexPath, at: .left, animated: true)
    currentCardIndex = autoSaveCards.count - 1

    setNewFirstResponder()
}

1条回答
Animai°情兽
2楼-- · 2019-08-20 17:04

Regarding case 2,3 i think that the cell is not yet loaded so if let fails , you can try to dispatch that after some time like this , also general note if the cell is not visible then it's nil

DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
   setNewFirstResponder()  
}

Also it can work if you set animated:false to scrollToItem

查看更多
登录 后发表回答