关于ios:当屏幕显示时,如何让键盘向上推?

How do I make a keyboard push the view up when it comes on screen? Xcode Swift

本问题已经有最佳答案,请猛点这里访问。

所以我有一个视图,其中有一个文本字段,但文本字段在底部。当我单击键盘时,它会弹出并覆盖文本字段,这是我的问题。我想知道当一个键盘出现时,是否有可能将视图的其余部分向上推?


您可以注册视图控制器,以便在键盘即将显示时得到通知,然后向上推视图。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class ViewController: UIViewController {

var keyboardAdjusted = false
var lastKeyboardOffset: CGFloat = 0.0

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    NSNotificationCenter.defaultCenter().addObserver(self, selector:"keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector:"keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}

override func viewDidDisappear(animated: Bool) {
    super.viewDidDisappear(animated)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}

func keyboardWillShow(notification: NSNotification) {
    if keyboardAdjusted == false {
        lastKeyboardOffset = getKeyboardHeight(notification)
        view.frame.origin.y -= lastKeyboardOffset
        keyboardAdjusted = true
    }
}

func keyboardWillHide(notification: NSNotification) {
    if keyboardAdjusted == true {
        view.frame.origin.y += lastKeyboardOffset
        keyboardAdjusted = false
    }
}

func getKeyboardHeight(notification: NSNotification) -> CGFloat {
    let userInfo = notification.userInfo
    let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
    return keyboardSize.CGRectValue().height
}

}

您可以检查本教程move uitextfield,这样键盘就不会隐藏它。

您可以在这里找到这个的演示

或者,当键盘显示为Swift时,可以检查此StackOverflow移动文本字段的答案。

最好的答案是通过更新这样的底部约束来管理

1
2
3
4
5
6
7
8
func keyboardWasShown(notification: NSNotification) {
     var info = notification.userInfo!
     var keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()

     UIView.animateWithDuration(0.1, animations: { () -> Void in
       self.bottomConstraint.constant = keyboardFrame.size.height + 20
  })
}


您应该将文本字段放入UIScrollView,并在UIKeyboardDidShowNotification上调整其contentInset

阅读本帮助页面:https://developer.apple.com/library/ios/documentation/stringstextfonts/conceptive/textandwebiphoneos/keyboardmanagement/keyboardmanagement.html//apple_-ref/doc/uid/tp40009542-ch5-sw7