在 Swift 中,当键盘出现时移动文本字段

swiftserver side programmingprogramming更新于 2025/8/16 7:37:17

在实际的 iOS 应用中,大多数情况下,您需要处理 UITextField 来接收各种输入。为了使文本字段在编辑时可见,您可以通过更新约束来管理它们。要管理约束,您必须添加用于键盘显示和隐藏的观察器。

在本文中,我们将按照以下步骤在键盘出现时移动文本字段。

步骤 1 - 基本设置

在此步骤中,我们将通过添加一个用于输入电子邮件地址的文本字段来进行一些基本设置。我们将在屏幕底部添加该文本字段,使其在键盘出现时可移动。

示例

import UIKit
class TestController: UIViewController {

   private lazy var emailTextField: UITextField = {
      let textField = UITextField()
      textField.keyboardType = .emailAddress
      textField.layer.cornerRadius = 8
      textField.layer.masksToBounds = true
      textField.layer.borderWidth = 1.0
      textField.layer.borderColor = UIColor(white: 0, alpha: 0.3).cgColor
      textField.placeholder = "Email Address"
      textField.textAlignment = .center
      textField.autocorrectionType = .no
      textField.delegate = self
      return textField
   }()
  
   private var textFieldBottomConstraint: NSLayoutConstraint?
   override func viewDidLoad() {
      super.viewDidLoad()
      initialSetup()
   }
   
   override func viewWillAppear(_ animated: Bool) {
      super.viewWillAppear(animated)

      // 添加键盘显示和隐藏的通知观察器
      NotificationCenter.default.addObserver(self,
      selector: #selector(keyboardWillShow),
      name: UIResponder.keyboardWillShowNotification,
      object: nil)
     
      NotificationCenter.default.addObserver(self,
      selector: #selector(self.keyboardWillHide),
      name: UIResponder.keyboardWillHideNotification,
      object: nil)
   }
   
   override func viewWillDisappear(_ animated: Bool) {
      super.viewWillDisappear(animated)
     
      // 删除所有通知观察者
      NotificationCenter.default.removeObserver(self)
   }
   
   private func initialSetup() {
   
    // 基本设置
    view.backgroundColor = .white
    navigationItem.title = "UITextField"
    
    // 为 emailTextField 添加约束
    view.addSubview(emailTextField)
    emailTextField.translatesAutoresizingMaskIntoConstraints = false
    emailTextField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 30).isActive = true
    emailTextField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -30).isActive = true
    emailTextField.heightAnchor.constraint(equalToConstant: 50).isActive = true
    textFieldBottomConstraint = emailTextField.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -100)
    textFieldBottomConstraint?.isActive = true
   }
   
   @objc private func keyboardWillShow(_ notification: NSNotification) {
   
      // 编写代码完成实现
   }
   
   @objc private func keyboardWillHide(_ notification: NSNotification) {
   
      // 编写代码完成实现
   }
   
   func updateViewWithKeyboard(notification: NSNotification,
   viewBottomConstraint: NSLayoutConstraint,
   keyboardWillShow: Bool) {
   
      // 编写代码完成实现
   }
}

输出

在上面的代码中,我们做了以下操作:

  • 向视图添加了一个电子邮件文本字段,并设置了一些约束。

  • 声明一个变量"textFieldBottomConstraint"来保存对电子邮件文本字段底部约束的引用。

  • 现在可以使用通知观察器来显示和隐藏键盘。在 viewWillAppear 方法中添加了这些观察器。

  • 移除 viewWillDisappear 中的通知观察器,以避免不必要的方法调用。

步骤 2 - 完成 keyboardWillShow 和 keyboardWillHide 方法的实现

在此步骤中,我们将完成这两个方法的代码。以下是这两个方法的完整代码。

@objc private func keyboardWillShow(_ notification: NSNotification) {
   
   //在编辑电子邮件文本字段时移动文本字段
   if emailTextField.isEditing {
      updateViewWithKeyboard(notification: notification,
      viewBottomConstraint: self.textFieldBottomConstraint!,
      keyboardWillShow: true)
   }
}
@objc private func keyboardWillHide(_ notification: NSNotification) {

   // 编辑完成后,将字段移回先前的位置
   updateViewWithKeyboard(notification: notification,
   viewBottomConstraint: self.textFieldBottomConstraint!,
   keyboardWillShow: false)
}

步骤 3 - 完成 updateViewWithKeyboard 方法的实现

我们将完成 updateViewWithKeyboard 方法的代码,以支持键盘移动并返回到之前的位置。代码如下。

private func updateViewWithKeyboard(notification: NSNotification,
viewBottomConstraint: NSLayoutConstraint,
keyboardWillShow: Bool) {

    // 获取键盘大小
    guard let userInfo = notification.userInfo,
    let keyboardSize = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else {
    return
    }
    
    // 获取键盘动画的时长
    guard let keyboardDuration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double else {
    return
    }
    
    // 获取键盘动画的曲线
    guard let keyboardCurve = UIView.AnimationCurve(rawValue: userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as! Int) else {
    return
    }
    
    // 获取键盘高度
    let keyboardHeight = keyboardSize.cgRectValue.height
    
    // 设置键盘显示和隐藏的常量
    if keyboardWillShow {
      viewBottomConstraint.constant = -(keyboardHeight + 50)
    } else {
      viewBottomConstraint.constant = -100
    }
    
    // 以与键盘动画相同的方式为视图添加动画
    let animator = UIViewPropertyAnimator(duration: keyboardDuration, curve: keyboardCurve) {
    [weak self] in self?.view.layoutIfNeeded()
    }
    
    // 执行动画
    animator.startAnimation()
}

在上面的代码中,我们做了以下操作:

  • 从通知对象提供的用户信息中获取键盘大小。

  • 从用户信息对象中获取键盘动画的持续时间。

  • 从用户信息对象中获取键盘动画的类型。

  • 获取键盘高度并更改 viewBottomConstraint 对象的常量值。

  • 通过执行 startAnimation 函数,使用 UIViewPropertyAnimator 类为视图添加动画方法。

输出

步骤 4 - 实现 UITextFieldDelegate 方法

在此步骤中,我们将实现委托方法,通过点击返回按钮来隐藏键盘。以下是代码。

extension TestController: UITextFieldDelegate {
    
   func textFieldShouldReturn(_ textField: UITextField) -> Bool {
      textField.resignFirstResponder()
   }
}

结论

要在键盘出现和消失时接收键盘通知,您可以使用键盘通知观察器。您可以从接收通知对象的 userInfo 对象中获取键盘高度以及其他值。获取键盘高度后,您可以使用常量属性更新约束值。



相关文章



关于我们 | 隐私条款 | 学习路线
返回顶部