I have a view controller A
which is currently in editing mode, i.e. it has a text field that is currently the first responder.
Now I present view controller B
from A
with a custom animator:
class Animator: NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 1
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
print("----- Transition Animation BEGIN -----")
guard let toView = transitionContext.view(forKey: .to) else {
return
}
transitionContext.containerView.addSubview(toView)
print("----- Transition Animation ADDED SUBVIEW -----")
toView.frame = transitionContext.containerView.bounds
toView.layoutIfNeeded()
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
For reasons of simplicity, this animator doesn't animate much: It only adds the destination view controller's view to the hierarchy and that's it.
View controller B
has a text field as well and when it appears on screen, I want it to become the first responder immediately. Thus I added this code to view controller B
:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
textField.becomeFirstResponder()
}
Now the interesting part is what happens between
----- Transition Animation BEGIN -----
and
----- Transition Animation ADDED SUBVIEW -----
1. Inside Rootview
When the text field in view controller A
is placed anywhere inside its root view, these are the keyboard notifications I receive from NotificationCenter
:
----- Transition Animation BEGIN -----
UIKeyboardDidChangeFrameNotification
UIKeyboardDidHideNotification
UIKeyboardWillChangeFrameNotification
UIKeyboardWillShowNotification
UIKeyboardDidChangeFrameNotification
UIKeyboardDidShowNotification
----- Transition Animation ADDED SUBVIEW -----
In other words: Adding the destination view controller's view to the transition's container view causes all these keyboard notifications to be fired. This is great because afterwards I can update B
's layout to account for the keyboard and also apply these layout changes to my transition animation.
2. Inside collection view cell
When the text field is placed inside a collection view cell of view controller A
, however, no keyboard notifications are received during the transition:
----- Transition Animation BEGIN -----
----- Transition Animation ADDED SUBVIEW -----
In any case, these are the notifications I receive before the transition animation begins:
UIKeyboardWillChangeFrameNotification
UIKeyboardWillHideNotification
This is problematic as in the second scenario view controller B
still "thinks" that the keyboard is hidden during the animation. Thus, I cannot layout its view and create the correct animations.