This question already has answers here:
How can I make a UITextField move up when the keyboard is present - on starting to edit?
(92个答案)
三年前关闭。
所以我有一个包含文本字段的视图,但是文本字段在底部。当我单击键盘时,它会弹出并覆盖文本字段,这是我的问题。我在想,当键盘出现时,是否有可能将视图的其余部分向上推?
(92个答案)
三年前关闭。
所以我有一个包含文本字段的视图,但是文本字段在底部。当我单击键盘时,它会弹出并覆盖文本字段,这是我的问题。我在想,当键盘出现时,是否有可能将视图的其余部分向上推?
最佳答案
您可以注册视图控制器,以便在键盘即将显示时收到通知,然后将视图向上推。
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
}
}
关于ios - 当屏幕上出现 View 时,如何使键盘将 View 向上推? Xcode Swift ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35561977/
10-13 08:00