我需要提供一个覆盖打开键盘的帮助屏幕 - 帮助屏幕应该调暗下面的整个视图并保持一个完全透明的小洞以“突出显示”该片段。关键是在突出显示几个视图组件时提供一些信息。如果没有键盘,我可以将视图放在层次结构的顶部,但在这种情况下,UI使用带有需要可见的自定义输入附件的键盘。
我尝试插入一个新的UIWindow
并将其置于UIWindow
的所有内容之上:
class CustomTextField: UITextField {
override var canResignFirstResponder: Bool {
return false
}
}
class ViewController: UIViewController {
var textField: UITextField = CustomTextField()
override func viewDidAppear(_ animated: Bool) {
view.backgroundColor = .white
super.viewDidAppear(animated)
textField.frame = CGRect(x: 0, y: 0, width: 200, height: 50)
view.addSubview(textField)
textField.backgroundColor = UIColor.gray
textField.becomeFirstResponder()
DispatchQueue.main.asyncAfter(wallDeadline: .now() + 1) {
self.window.windowLevel = 100000002.0 // based on experiments with UIApplication.shared.windows this should be the top most window
let controller = UIViewController()
controller.view.backgroundColor = UIColor.black.withAlphaComponent(0.5)
self.window.rootViewController = controller
self.window.makeKeyAndVisible()
}
}
let window = UIWindow(frame: UIScreen.main.bounds)
}
但这种方法存在两个问题:
windowLevel = 100000002.0
,似乎键盘位于窗口上方(键盘也会生成动画,因此在隐藏时,我可以看到它位于我的窗口上方。)任何想法如何处理这两个问题?它甚至可能吗?
答案 0 :(得分:1)
好的,正如@Krunal指出的那样,这是this question的重复。诀窍是将叠加视图添加到键盘所在的窗口(恰好是UIApplication.shared.windows.last
):
class ViewController: UIViewController { var textField: UITextField = UITextField() override func viewDidAppear(_ animated: Bool) { view.backgroundColor = .white super.viewDidAppear(animated) textField.frame = CGRect(x: 0, y: 0, width: 200, height: 50) view.addSubview(textField) textField.backgroundColor = UIColor.gray textField.becomeFirstResponder() DispatchQueue.main.asyncAfter(wallDeadline: .now() + 1) { // this does the trick let customView = UIView(frame: self.view.bounds) customView.backgroundColor = UIColor.black.withAlphaComponent(0.5) customView.layer.zPosition = CGFloat(Float.greatestFiniteMagnitude) UIApplication.shared.windows.last?.addSubview(customView) } } }