我从这个现有的问题中学到了让func"keyboardwillshow"将整个视图向上移动与键盘相同的高度,以避免底部的文本字段/文本视图被键盘覆盖。
但是,如果我连续点击两个或多个文本字段,"keyboardwillshow"功能将通过相同数量的点击运行,进一步向上移动视图并最终离开屏幕,只留下黑色的空虚。
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) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
self.view.frame.origin.y -= keyboardSize.height
}
}
func keyboardWillHide(notification: NSNotification) {
self.view.frame.origin.y = 0
}
有人在答案中说,我们可以实现一个布尔值来检测键盘是否已经出现,所以func只会工作一次。
有人可以告诉我如何做这个布尔值吗?谢谢!
首先添加一个实例变量来存储布尔值并初始化为 false ( var keyboardIsShown = false
.接下来,在 keyboardWillShow
中的 if 语句中,将您之前创建的boolean
设置为 true
,因为现在已显示键盘。下一步是在移动视图之前向 keyboardWillShow
中添加另一个 if 语句,以检查键盘是否已显示。最后,确保在再次隐藏键盘时将boolean
设置回false
。
// instance variable here
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) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
// if statement here
self.view.frame.origin.y -= keyboardSize.height
// set boolean to true
}
}
func keyboardWillHide(notification: NSNotification) {
self.view.frame.origin.y = 0
// set boolean to false
}
好的。我想出更好的解决方案是使用 UITextFieldTextDidBeginEditorNotification 和 UITextViewTextDidBeginEditorNotification,或 UITextViewTextDidBeginEditNotification 和 UITextViewTextDidEndEditNotification。
例:
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UITextFieldTextDidBeginEditingNotification, object: yourTextField)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UITextFieldTextDidEndEditingNotification, object: yourTextView)
这样,键盘行为仅适用于标识为 object: 的指定文本字段或文本视图。如果您希望它适用于视图中的所有文本字段或文本视图,则对象为 nil。