ios - iOS - 当视图控制器以模态方式呈现时,如何将视图保持在前面?
问题描述
TestView
我有一个导航 ViewController,当用户关闭互联网时,我想添加一个在所有 ViewControllers 上命名的自定义视图。当 Internet 连接状态发生变化时,我将自定义视图添加到 keyWindow。当我推送 ViewController 时,视图会显示并停留在那里,但是当我以模态方式呈现 ViewController 时,模态 ViewController 会覆盖视图。
即使以模态方式呈现 VC,我也希望视图保持在最前面,并且我希望能够在我的 AppDelegate 文件中为所有模态 ViewControllers 或类似的东西添加一些代码。我怎样才能在 swift 5 中做到这一点?我在想如果每次呈现模态 VC 时都会触发一个函数,我可以在那里添加我的代码。这是我的 AppDelegate 目前的样子:
class AppDelegate: UIResponder, UIApplicationDelegate, ReachabilityObserverDelegate {
var reachability: Reachability?
var window: UIWindow?
var internetView: TestView?
//This is called when the internet connects or disconnects
func reachabilityChanged(_ isReachable: Bool) {
window = getKEYWindow()
if !isReachable {
window?.addSubview(internetView!)
}
else {
internetView?.removeFromSuperview()
}
}
func getKEYWindow() -> UIWindow? {
return UIApplication.shared.connectedScenes.filter({$0.activationState == .foregroundActive}).map({$0 as? UIWindowScene}).compactMap({$0}).first?.windows.filter({$0.isKeyWindow}).first
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
try? addReachabilityObserver()
internetView = TestView(frame: CGRect(x:0, y: 50, width: UIScreen.main.bounds.size.width, height: 14))
return true
}
}
更新:我找到了另一种保持视野领先的方法。我添加了以下行internetView.layer.zPosition = .greatestFiniteMagnitude
,didFinishLaunchingWithOptions
它就像一个魅力。谢谢大家的帮助。
解决方案
我可以建议一种方法:
打开更高级别的新 UIWindow 并将其绘制在整个应用程序之上。
我不知道这是否是最好的方法,但是我只是在一个空的应用程序上使用以下代码对其进行了测试——它似乎有效——甚至可以是透明的。
_myWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
[_myWindow makeKeyAndVisible];
UIViewController* dummyVC = [[UIViewController alloc] init];
dummyVC.view = [[UIView alloc]initWithFrame:_myWindow.bounds];
[dummyVC.view setOpaque:NO];
[dummyVC.view setAlpha:0.1f];
[_myWindow setRootViewController:dummyVC];
_myWindow.windowLevel = UIWindowLevelAlert + 1;
[_myWindow.rootViewController.view.layer setBackgroundColor:[UIColor greenColor].CGColor];
推荐阅读
- javascript - 多年来的 javascript 利息计算器
- c++ - 提高驱动程序的时间效率
- ios - 无法使用方法 swizzling 打印当前 ViewController 名称
- azure-devops - 如何将 Azure Devops 组织迁移到不同的租户
- typescript - 在 Typescript 中使用 SinonJS 时,私有属性被报告为缺失
- unicode - 原始字符和unicode之间排序顺序不同的示例?
- android - 如何从 SQLite 中选择数字/字符大于某个值的行
- mongodb - 嵌套数组中的MongoDB聚合$size
- api - 如何从 API 获取所有用户从 Slack 执行的最后一个活动时间戳
- android - 连接时的 SQLite 相同的列名