📅  最后修改于: 2023-12-03 15:28:35.898000             🧑  作者: Mango
在 Swift 中,当弹出键盘时,我们通常需要将视图上移,以便用户可以看到正在编辑的文本框。快速视图浮动是一种方便的方法,可以轻松实现这一目的。
在开始使用快速视图浮动之前,请确保您已经将以下内容添加到您的 Swift 项目中:
import UIKit
var activeField: UITextField?
这个属性将跟踪当前正在编辑的文本框。
@objc func keyboardWillShow(notification:NSNotification){
if let activeField = self.activeField {
if ((notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size.height) != nil {
let info = notification.userInfo!
let keyboardFrame: CGRect = (info[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let keyboardHeight = keyboardFrame.size.height
let contentInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardHeight, right: 0.0)
self.scrollView.contentInset = contentInsets
self.scrollView.scrollIndicatorInsets = contentInsets
var aRect: CGRect = self.view.frame
aRect.size.height -= keyboardHeight
let activeFieldRect: CGRect? = activeField.frame
let activeFieldOrigin: CGPoint? = activeFieldRect?.origin
if (!aRect.contains(activeFieldOrigin!)) {
self.scrollView.scrollRectToVisible(activeFieldRect!, animated:true)
}
}
}
}
@objc func keyboardWillHide(notification:NSNotification){
let contentInsets : UIEdgeInsets = UIEdgeInsets.zero
self.scrollView.contentInset = contentInsets
self.scrollView.scrollIndicatorInsets = contentInsets
}
viewDidLoad()
函数中,将以下代码添加为观察者,以便我们可以接受键盘事件通知:NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
shouldReturn
函数中,以使文本框释放第一响应者:textField.resignFirstResponder()
activeField = nil
现在,您应该已经成功地实现了 Swift 中的快速视图浮动。此功能将使您的应用程序更加便于使用,并提高用户体验。