Jogga
Jogga

Reputation: 23

Why is a UIView whose frame I change after receiving a UIKeyboardWillShowNotification automatically animated?

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

Further questions

Upvotes: 2

Views: 379

Answers (1)

Roger Oba
Roger Oba

Reputation: 1410

The answers:

  • Yes, because the code inside those notifications are meant to be used exclusively to animate your view to respond to the keyboard's appearance, like to scroll scroll views, or move text fields to its correct place.
  • I couldn't find anything but the documentation of the keyboard notifications available here
  • Synchronizing Animations in keyboardWillShow keyboardWillHide -- Hardware Keyboard & Virtual Keyboard Simultaneously - related question
  • To disable these animations, call the didShow and didHide notifications, since they are meant to contain code to be executed after the animation have commited.
  • Yes.
  • As long as you work well with the keyboard animations, yes! But those notifications are meant to be used to deal with the keyboard animation interaction inside the view, and not other unrelated animations. You should those unrelated animation views you're trying to animate inside a scroll view and scroll it accordingly when receiving the keyboard notifications, to have a better experience.

Hope I helped.

Upvotes: 1

Related Questions