我有一个自定义UIView
,这是UIViewController
上的子视图。
我把它添加到我的故事板中并将其设置为隐藏。
我的子视图也在另一个UIView
中,我用它作为'模糊视图',最初也是隐藏的。
我有一些功能可以取消隐藏和隐藏子视图。
我的自定义子视图有一个UITextField
。我可以显示键盘并毫无问题地移动子视图。当我键入键盘或关闭它时,我的子视图向上移动到左侧。当我再次尝试显示我的子视图时,它显示不正确(向上和向左)。
自定义子视图从我的屏幕中心开始。
目标是在键盘显示时将其向上移动,以便它不会覆盖子视图或UITextField
,允许用户键入UITextField
,然后关闭键盘并将自定义子视图移回中心。
在我的UIViewController中:
// Showing the custom sub view
func displayCustomSubView() {
if let window = UIApplication.shared.keyWindow {
self.blurView.isHidden = false
self.customSubView.isHidden = false
self.blurView.frame = window.frame
self.customSubView.center = window.center
window.addSubview(self.blurView)
UIApplication.shared.keyWindow?.bringSubviewToFront(self.blurView)
}
}
// Hiding the custom sub view
// the custom sub view has a button I tap to hide
@objc func dismissCustomSubView() {
self.blurView.isHidden = true
self.customSubView.isHidden = true
}
// Show Keyboard
// Since I am using the window to make sure my blur view expands to the full frame, I have tried just moving the window up
@objc func keyboardWillShow(sender: NSNotification) {
if let window = UIApplication.shared.keyWindow {
window.frame.origin.y = -75
}
}
// Hide Keyboard
@objc func keyboardWillHide(sender: NSNotification) {
if let window = UIApplication.shared.keyWindow {
window.frame.origin.y = 0
}
}
// Custom Subview Extension
extension CustomSubView: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
添加了上面的自定义子视图扩展。
首先在viewDidLoad()中添加此通知。并创建一个名为var keyboardH: CGFloat = 0
的全局变量:
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillShow),
name: UIResponder.keyboardWillShowNotification,
object: nil
)
而这个功能如下:
@objc func keyboardWillShow(_ notification: Notification) {
if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
self.keyboardH = keyboardHeight
}
每次键盘存在时都会调用此函数,并显示键盘高度,之后我们可以使用此变量。
所以在你的代码中:
@objc func keyboardWillShow(sender: NSNotification) {
if let window = UIApplication.shared.keyWindow {
let position = window.frame.origin.y - keyboardH
window.frame.origin.y = position
}
}