作者:蓝羽月妞妞 | 来源:互联网 | 2023-05-17 10:26
Iwouldliketoknowisitpossibleto,letsay,changeormodifyanobjectlikeabuttonofanother
I would like to know is it possible to, let say, change or modify an object like a button of another view controller from AppDelegate.swift
. Here is what I tried to begin with but somehow stucked.
我想知道是否可以改变或修改对象,如AppDelegate.swift中另一个视图控制器的按钮。这是我试图开始但不知何故被卡住了。
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
}
}
}
Any help is appreciated. Thanks in advance.
任何帮助表示赞赏。提前致谢。
4 个解决方案
1
It is possible, but addressing directly members of another ViewController breaks responsibility. It is a good practice to define Interface protocols for internal interactions. In this particular case, it is a good idea to create protcol RemoteNotificationReciverInterface (or kind of RemoteNotificationReciveable according to some modern coding styles advice, although I found it difficult to find appropriate adjective in this case) :
这是可能的,但直接解决另一个ViewController的成员会破坏责任。为内部交互定义接口协议是一种很好的做法。在这种特殊情况下,根据一些现代编码样式建议创建protcol RemoteNotificationReciverInterface(或者RemoteNotificationReciveable的类型是一个好主意,尽管我发现在这种情况下很难找到合适的形容词):
protocol RemoteNotificationReciverInterface: class {
func didReciveNotification(info : [AnyHashable : Any])
}
Then extent your ViewController( and any view controllers that had to react on Notifications when they are topmost)
然后扩展您的ViewController(以及任何视图控制器,当它们位于最顶层时必须对通知作出反应)
extension HomeViewController: RemoteNotificationReciverInterface {
func didReciveNotification(info : [AnyHashable : Any]) {
// Chnage you button, ignore para,eters
}
}
You can adopt UINavigationContoroller, UITabBarConroller etc. to forward notifications to their topmost controllers, like:
您可以采用UINavigationContoroller,UITabBarConroller等将通知转发给最顶层的控制器,例如:
extension UINavigationController: RemoteNotificationReciverInterface {
func didReciveNotification(info : [AnyHashable : Any]) {
(topViewController as? RemoteNotificationReciverInterface)?.didReciveNotification(info: info)
}
}
And the easily forward it from app delegate.
并且可以从app delegate轻松转发它。
func application(_ application: UIApplication,didReceiveRemoteNotification userInfo: [AnyHashable : Any],fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
if application.applicatiOnState== .active {
(window?.rootViewController as? RemoteNotificationReciverInterface).didReciveNotification(info: userInfo)
}
}