Search code examples
swiftuicollectionviewuitextfieldcustom-cell

How to trigger action when textfield becomes active


I have a CollectionViewController made up of custom cells. At this point my custom cells are only made up of UITextFields. When I click inside one of the textFields to begin typing I want to trigger an animation on the cell. For some reason I can't figure out why my animation isn't being triggered when I click inside the textField. When I conform to the UItextFieldDelegate protocol and try to trigger the action through the DidBeginEditing method it doesn't work. When I try to trigger the animation through UIControlEvents.touchDown it isn't working either.

@objc func animateCell(textField: UITextField) {  
    print("TextField active")
   let cell = collectionView.cellForItem(at: indexPath)
   UIView.animate(withDuration: 0.5, delay: 0, options: .allowAnimatedContent, animations: ({
   cell?.frame = collectionView.bounds
    collectionView.isScrollEnabled = false
  }), completion: nil)
}

Solution

  • Instead of textFieldDidBeginEditing, try using textFieldShouldBeginEditing: (and make sure to return true from that method since you want to allow the user to type :-).

    Also, since you say the method doesn't fire until you click on a different textfield outside of the first one selected, fire the animation manually for the initially selected text field as the collection view is displayed.