[英]Move up textfield above the keyboard
我尝试使用某种方式使视图向上移动,因为当我进入表单末尾并点击最后一个文本字段时,由于键盘出现在文本字段上方,所以我看不到我写的内容,因此我发现了一些东西,但在这里,如果我点击视图顶部的文本字段,则将其向上隐藏,这是代码:
override func 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) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
self.view.frame.origin.y += keyboardSize.height
}
}
但是这里还有另一个问题,当我在另一个文本字段中点击两次时,会出现一个黑色的块。
因此,我不想做的是检测文本字段并将键盘放在其下方,以便将文本字段向上移动。 并检测键盘是否已经在这里,不要显示黑色方块。 但是我还没有找到解决方案。
我在我的项目中使用了以下代码:
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
// Register Keyboard Notification
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
// Remove Keyboard notification observer
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func keyboardWillShow(notification: NSNotification)
{
var userInfo = notification.userInfo!
var keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()
keyboardFrame = self.view.convertRect(keyboardFrame, fromView: nil)
var contentInset:UIEdgeInsets = self.scrollView.contentInset
contentInset.bottom = keyboardFrame.size.height - 30 //Set this value (30) according to your code as i have navigation tool bar for next and prev.
self.scrollView.contentInset = contentInset
}
func keyboardWillHide(notification: NSNotification) {
let contentInset:UIEdgeInsets = UIEdgeInsetsZero
self.scrollView.contentInset = contentInset
}
希望对你有帮助!!
添加布尔属性self.isKeyBoardUp
在keyboardWillShow中:如果isKeyBoardUp返回,则将其设置为true并执行您的工作。
在keyboardWillHide中:如果不是isKeyBoardUp返回,则将其设置为false并执行您的操作。
请检查此代码,我正在尝试并尝试从中获取此代码
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
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.