我在var scrollview: UIScrollView
中制作了30个文本字段和viewDidLoad()
,并且当键盘覆盖文本字段时,我试图向上移动整个滚动视图。已设置Delegate
个textfields和scrollview。
当键盘第一次出现时,此代码(下方)工作,scrollview向上移动,但问题是,当键盘第二次打开或更多时,scrollview不会向上移动。我无法解决这个问题几个小时。任何人都可以检测到我的代码中的一些错误并给我正确答案吗?我期待着任何帮助!
我写的代码是:
var activeField: UITextField?
func registerForKeyboardNotifications(){
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notificaiton:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func deregisterForKeyboardNotifications(){
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name:NSNotification.Name.UIKeyboardWillHide, object: nil)
}
@objc func keyboardWasShown(notificaiton: NSNotification){
var info = notificaiton.userInfo!
let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
let contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0)
var aRect: CGRect = view.frame
aRect.size.height -= keyboardSize!.height
if let activeField = activeField{
if !aRect.contains(activeField.frame.origin) == true{
scrollview.contentInset = contentInsets
}
}
}
@objc func keyboardWillBeHidden(notification: NSNotification){
view.endEditing(true)
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool{
activeField = textField
registerForKeyboardNotifications()
return true
}
func textFieldDidEndEditing(_ textField: UITextField){
activeField = nil
deregisterForKeyboardNotifications()
}
答案 0 :(得分:5)
朋友请试试这段代码。希望它也适合你。我正在使用它并且效果很好。
KeyDown
我已经为swift 4.0编写了这段代码。
答案 1 :(得分:0)
管理多个文本字段滚动并在每个视图控制器中添加多行代码确实占用了大部分开发时间,但幸运的是我们有一个替代解决方案,代码数量较少使用此libarary
您只需在didFinishLaunchingWithOptions
IQKeyboardManager.sharedManager().enable = true
这将处理整个项目键盘
希望这会对你有所帮助
答案 2 :(得分:0)
只需使用IQKeyboardManager
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
IQKeyboardManager.shared.enable = true
return true
}}