【发布时间】:2019-07-23 18:43:03
【问题描述】:
我有一个自定义 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
}
}
在上面添加了自定义子视图扩展。
【问题讨论】:
-
我们可以看到自定义子视图文本字段委托函数吗?
标签: swift keyboard uitextfield subview uiwindow