change autolayout constant when keyboard shows

时间:2016-08-31 18:22:04

标签: ios swift2 autolayout

I'm having a TopContainer View then a Scrollview and then again a BottomContainer view.

Now The constraints are that the scrollviews top is to the bottom of topContainer and that the bottom of the scrollview is to the top off the bottomcontainer.

When I start the viewcontroller and see the view hierarchy it is good.

But then when the keyboard shows I want to modify the autolayout constraint so that the bottomcontainer moves up.

So I thought I save the constraint and the change the constant like this:

private var toolbarBottomConstraint: NSLayoutConstraint?
self.toolbarBottomConstraint = self.toolbar.autoPinEdgeToSuperviewEdge(.Bottom, withInset: 0)

And then when the keyboard popups up I do this:

func keyboardWillShow(notification:NSNotification){
    var userInfo = notification.userInfo!
    var keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()
    keyboardFrame = self.view.convertRect(keyboardFrame, fromView: nil)

    self.toolbarBottomConstraint?.constant = keyboardFrame.size.height
}

This doesn't do anything. The keyboard height is exactly the offset the bottom needs to be on top of the keyboard.

Why is the view not changing? I always change constants like that and it always works. Do I need to do something special because it's now with the keyboard.

2 个答案:

答案 0 :(得分:1)

Have you tried calling setNeedsLayout() after the set of the constraint?:

self.toolbarBottomConstraint?.constant = keyboardFrame.size.height
self.view.setNeedsLayout()

答案 1 :(得分:1)

If you're building for iOS 9 or above, I wrote a simple library that takes care of automatically adjusting views when a keyboard appears. It's pretty flexible and it should work seamlessly.

If you do still want to roll this on your own, it looks like you haven't added a listener for the notification anywhere. You'll need to do that before messages are sent to the keyboardWillShow(_:) method.