我需要呈现一个覆盖打开键盘的帮助屏幕 - 帮助屏幕应该使下面的整个 View 变暗,并仅保留一个完全透明的小孔以“突出显示”该部分。重点是在突出显示多个 View 组件的同时提供有关它们的一些信息。如果没有键盘,我可以将 View 放在层次结构的顶部,但在本例中,UI 使用带有需要可见的自定义输入附件的键盘。
我尝试插入新的 UIWindow
并将其放在所有 UIWindow
之上s:
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
键盘似乎位于窗口上方(键盘会变得动画,因此在隐藏时,我可以看到它位于窗口上方)。
有什么想法可以解决这两个问题吗?这可能吗?
最佳答案
好的,正如 @Krunal 所指出的,这是 this question 的重复。 。诀窍是将覆盖 View 添加到键盘所在的窗口(恰好是 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) } } }
关于ios - 如何在 iOS 中将 View 覆盖在键盘上方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48564660/