gpt4 book ai didi

ios - 从 UIApplication 子类呈现一个 ViewController

转载 作者:行者123 更新时间:2023-11-28 07:49:29 24 4
gpt4 key购买 nike

我的 UIApplication 子类中有一个计时器在运行,它应该在用完时将用户发送到某个 ViewController

我能够实例化我想去的 ViewController...

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "StartVC")

...但我不知道如何实际呈现它。AppDelegate 中我可以做 window.rootViewController 等. 但这在我的 UIApplication 子类中不可用。

我也尝试过 self.windows[0].rootViewController 但这始终只是第一个 ViewController,它在应用程序启动时出现。与 self.keyWindow.rootViewController 相同。老实说,我不知道这两个属性是什么。

上下文的完整代码:

import Foundation
import UIKit

class MyApplication: UIApplication {

var inactivityTimer: Timer!

override init() {
super.init()
restartInactivityTimer()
}

@objc func timerExceeded() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "StartVC")
//...here I would need to present "vc"
}

override func sendEvent(_ event: UIEvent) {
super.sendEvent(event)
restartInactivityTimer()
}

func restartInactivityTimer() {
if inactivityTimer != nil { inactivityTimer.invalidate() }
inactivityTimer = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(timerExceeded), userInfo: nil, repeats: false)
}
}

最佳答案

实现不活动计时器不需要子类化 UIApplication。根据 UIApplication documentation 的子类化说明,只有在极少数情况下才需要子类化:

Most apps do not need to subclass UIApplication. Instead, use an app delegate to manage interactions between the system and the app.

If your app must handle incoming events before the system does—a very rare situation—you can implement a custom event or action dispatching mechanism. To do this, subclass UIApplication and override the sendEvent(:) and/or the sendAction(:to:from:for:) methods. For every event you intercept, dispatch it back to the system by calling [super sendEvent:event] after you handle the event. Intercepting events is only rarely required and you should avoid it if possible.

正如您在问题中已经提到的,您可以从/通过 AppDelegate 访问所需的一切。那么,为什么不在 AppDelegate 中/通过 AppDelegate 处理不活动超时呢?

关于ios - 从 UIApplication 子类呈现一个 ViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50092000/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com