I noticed a surprising behavior: When I change the frame of a UIView
after receiving the UIKeyboardWillShowNotification
or UIKeyboardWillHideNotification
, the change of the frame is animated. It seems like this animation uses the same duration and easing curve as the keyboard. In this project, I don't use Autolayout, I'm laying views out programmatically by setting their frames.
Can someone explain to me what is going on here?
Code
The interesting parts of the UIViewController's viewDidLoad()
:
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillShow), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillDisappear), name: UIKeyboardWillHideNotification, object: nil)
someView.frame = CGRect(origin: CGPoint(x: 0, y: view.bounds.height - 10), size: CGSize(width: 10, height: 10))
someView.backgroundColor = UIColor.redColor()
view.addSubview(someView)
The callbacks:
func keyboardWillShow(notification: NSNotification) {
someView.frame.origin = CGPoint(x: 0, y: 0)
}
func keyboardWillDisappear(notification: NSNotification) {
someView.frame.origin = CGPoint(x: 0, y: view.bounds.size.height - someView.bounds.size.height)
}
Further details
- The callbacks are called only once.
- I'm using a standard UIViewController.
- I'm not getting an animation in callbacks from the
UIKeyboardDid...
notifications - I can prevent the automatic animations by calling
UIView.commitAnimations()
before setting my UIViews Frame, but this seems hacky. - Autolayout shouldn't be involved, as I'm laying the views out by setting their frames
Further questions
- Is this expected behavior?
- Is it documented somewhere?
- Is there a good way to disable animations like these?
- Is it save to rely on this behavior?
- Can I safely play custom animations when receiving a
UIKeyboardWill...
notification?