1

是否有一种优雅的方式可以将位于其父视图底部的UIView(即 a )无缝移动到键盘的?UIButtoninputAccessoryView

我设想键盘基本上是在滑入时拿起按钮并将其向上拖动。请参阅下面的模型。显然,我希望这也能反过来工作。

我知道如何分别做,但我不知道如何结合起来。有谁以前这样做过吗?

谢谢!

想法的例证

更新:我忘了提到我主要在UIScrollViews. 虽然下面安德烈的答案适用于普通视图,但在将其与滚动视图一起使用时会中断。

4

1 回答 1

4

在这种情况下,您可以忽略使用 inputaccessoryview,而是调整登录按钮对键盘通知的底部约束。

class ViewController: UIViewController {
  @IBOutlet weak var signInButtonBottomConstraint: NSLayoutConstraint!

  override func viewDidLoad() {
    super.viewDidLoad()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)
  }

  func keyboardWillShow(notification: NSNotification) {
    let userInfo = notification.userInfo!

    let animationDuration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double
    let keyboardEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()

    signInButtonBottomConstraint.constant = keyboardEndFrame.height
    UIView.animateWithDuration(animationDuration) { () -> Void in
      self.view.layoutIfNeeded()
    }
  }

  func keyboardWillHide(notification: NSNotification) {
    let userInfo = notification.userInfo!

    let animationDuration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double

    signInButtonBottomConstraint.constant = 0.0
    UIView.animateWithDuration(animationDuration) { () -> Void in
      self.view.layoutIfNeeded()
    }
  }
}
于 2015-11-12T20:00:07.187 回答