<分区>
所以我有一个带有文本字段的 View ,但文本字段位于底部。当我单击键盘时,它会弹出并覆盖文本字段,这是我的问题。我想知道是否有可能在键盘出现时将 View 的其余部分向上推?
<分区>
所以我有一个带有文本字段的 View ,但文本字段位于底部。当我单击键盘时,它会弹出并覆盖文本字段,这是我的问题。我想知道是否有可能在键盘出现时将 View 的其余部分向上推?
最佳答案
您可以注册您的 View Controller ,以便在键盘即将显示时收到通知,然后将您的 View 向上推。
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/