问题在于,当我尝试在文本字段中写入时,键盘会覆盖它们。如何向上滚动文本字段以查看我在写什么。我在下面的代码行中启用了返回键,并在您触摸其他位置时隐藏键盘:
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
答案 0 :(得分:4)
如何向上滚动文本字段以查看我在写什么
这可以通过两种方式实现:
IQKeyBoardManager
,其Swift变体为 IQKeyboardManagerSwift
您可以在GitHub和cocoapods <找到它/ LI>
醇>
要实现以下步骤:
SWIFT 3
只需从Github或cocoapods安装IQKeyboardManagerSwift
在IQKeyboardManagerSwift
Appdelegate
在AppDelegate didFinishLaunchingWithOptions
方法中添加以下代码行。
IQKeyboardManager.sharedManager().shouldResignOnTouchOutside = true;
<强>目标C 强>
IQKeyBoardManager
#import "IQKeyboardManager.h"
Appdelegate
在AppDelegate didFinishLaunchingWithOptions
方法中添加以下代码行。
IQKeyboardManager.sharedManager.shouldResignOnTouchOutside = true;
这是完成。这是您需要编写的唯一代码。
答案 1 :(得分:0)
解决此问题的最简单方法是将所有元素放入一个scrollview,然后将键盘高度添加到视图底部的常量以进行超视图。
当显示或隐藏键盘时,iOS会向任何已注册的观察者发出以下通知:
UIKeyboardWillShowNotification UIKeyboardDidShowNotification UIKeyboardWillHideNotification UIKeyboardDidHideNotification
以下是您可以做的事情:
这样的事情:
func keyboardWillShow(notification: NSNotification) {
print("KEYBOARD WILL SHOW")
let userInfo:NSDictionary = notification.userInfo! as NSDictionary
let keyboardFrame:NSValue = userInfo.value(forKey: UIKeyboardFrameEndUserInfoKey) as! NSValue
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
bottomConstraint.constant = keyboardHeight + 8
UIView.animate(withDuration: 0.5, animations: { [weak self] in
self?.view.layoutIfNeeded() ?? ()
})
UIView.animate(withDuration: 0.3) {
self.view.layoutIfNeeded()
}
}
func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
bottomConstraint.constant = 8
UIView.animate(withDuration: 0.5, animations: { [weak self] in
self?.view.layoutIfNeeded() ?? ()
})
}
答案 2 :(得分:0)