如何解决Swift 3中的键盘问题?

问题是,当我试图写在文本字段的键盘覆盖起来。 我怎样才能滚动文本字段,看看我在写什么。 我有下面的代码行来启用返回键,并在不同的地方触摸时隐藏键盘:

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 } 

我怎样才能滚动文本字段,看看我在写什么

这可以通过两种方式来实现:

  1. 您可以在键盘上以编程方式pipe理您的框架,并像@Taichi Kato一样显示
  2. 您可以整合符合相同目的的图书馆。 一个这样的库是IQKeyBoardManager ,它的Swift变体是IQKeyboardManagerSwift你可以在GitHub和cocoapods上find它

要实现以下步骤:

SWIFT 3

  1. 只需从Github或cocoapods安装IQKeyboardManagerSwift

  2. Appdelegate导入Appdelegate

  3. AppDelegate didFinishLaunchingWithOptions方法中添加下面的代码行。

     IQKeyboardManager.sharedManager().shouldResignOnTouchOutside = true; 

Objective-C的

  1. 通过任何介质安装IQKeyBoardManager
  2. Appdelegate导入#import "IQKeyboardManager.h"
  3. AppDelegate didFinishLaunchingWithOptions方法中添加下面的代码行。

     IQKeyboardManager.sharedManager.shouldResignOnTouchOutside = true; 

这是完成的 。 这是您需要编写的唯一代码。

这个问题的最简单的解决scheme是把所有的元素放到一个滚动视图中,然后将键盘高度添加到视图底部的常量来超级查看。

当键盘显示或隐藏时,iOS向任何注册的观察者发送以下通知:

UIKeyboardWillShowNotification UIKeyboardDidShowNotification UIKeyboardWillHideNotification UIKeyboardDidHideNotification

所以这里是你可以做的:

  1. 获取键盘的大小。
  2. 通过键盘高度调整滚动视图的底部内容插入。
  3. 将目标文本字段滚动到视图中。

像这样的东西:

  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() ?? () }) }