我想知道是否可以从 AppDelegate.swift
更改或修改一个对象,例如另一个 View Controller 的按钮。
这是我尝试开始但不知何故卡住了。
func application(_ application: UIApplication,didReceiveRemoteNotification userInfo: [AnyHashable : Any],fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
if application.applicationState == .active {
if self.window?.rootViewController is homeViewController {
//modify a button exist in homeViewController
}
}
}
感谢任何帮助。提前致谢。
最佳答案
您可以使用 NotificationCenter 发送和接收内部通知(注意它们不同于本地和远程通知)。
首先创建你的通知做这样的事情:
extension Notification.Name {
static let remoteNotificationReceived = Notification.Name("uk.co.company.app.remoteNotificationReceived")
}
然后在要响应的 View Controller 中执行如下操作:
class TestViewController: UIViewController {
var remoteNotificationReceivedObserver: NSObjectProtocol?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
remoteNotificationReceivedObserver = NotificationCenter.default.addObserver(forName: Notification.Name.remoteNotificationReceived, object: nil, queue: nil, using: { (notification) in
DispatchQueue.main.async { // because the notification won't be received on the main queue and you want to update the UI which must be done on the main queue.
// Put the code to change the button here
}
})
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if let remoteNotificationReceivedObserver = remoteNotificationReceivedObserver {
NotificationCenter.default.removeObserver(remoteNotificationReceivedObserver)
}
}
}
然后在您应用的其他地方,您可以像这样发布通知:
NotificationCenter.default.post(name: Notification.Name.remoteNotificationReceived, object: nil)
关于ios - 修改另一个 View Controller 的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48166844/