Search code examples
iosswiftuitextfielduicollectionviewcell

How to identify which UITextField is being modified inside a UICollectionView Cell?


I have a some UITextFields inside a UICollectionViewCell and I want to know which of them is being modified. Every element has been made programmatically. The UICollectionViewCell has a swift class. The cell is repeated inside the UICollectionView about 5 times so I need to also in which cell the UITextField is.

Any suggestion about it?


Solution

  • First, in cellForItemAt, you need to assign a tag to the textView that will be displayed in that cell. It's easiest to identify it with the row number of the cell. For example:

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        cell.textView.tag = indexPath.row
    }
    

    Next, inside textViewDidChange you put in a switch statement corresponding with the tag of the textView being modified. Inside each case you can perform whatever code you need knowing which textView you are modifying. For example:

    func textViewDidChange(_ textView: UITextView) {
        switch textView.tag {
        case 0:
            // Code for first text view
            break
        case 1:
            // Code for second text view
            break
        case 2:
            // Code for third text view
            break
        case 3:
            // Code for fourth text view
            break
        default:
            // Code for fifth text view
            break
        }
    }