ios - 修改另一个 View Controller 的对象

标签 ios swift uiviewcontroller appdelegate

我想知道是否可以从 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/

相关文章:

ios - 如何让编辑菜单出现在具有 contentEditable 的 UIWebView 中?

iphone - 为 iOS 3 编译的应用程序能否在 iOS 4 和 ios5 上运行?

ios - UIP 英寸手势 ?为什么只有在旋转设备后才显示缩放结果

仅限 iOS 10 : Viewcontroller in pageviewcontroller hidden behind tabbar

ios - 如何在不离开屏幕的情况下结束长按手势?

iphone - 从深度嵌套的 UIControl 向 View Controller 发送消息的最佳方式?

ios - Phonegap - 第一个应用程序

ios - 如何正确编码 URL 字符串

iphone - 取消调度队列

ios - 在 iOS 13 的 iPhone 上将纵向 View Controller 推到横向 View Controller 上