如何从 app delegate 打开我的段控制器的段索引?

How do I open the segment index of my segment controller from app delegate?

我想在打开本地通知时显示 "Menu View Controller"。我在 "Menu View Controller" 中使用了一个段控件,当通过本地通知打开视图时,应将其设置为 selectedSegmentIndex = 0。我可以打开 View Controller,但我不知道如何处理来自应用程序委托的段控制? 这是我使用的代码:

 // open the menu view controller when notification is pressed

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

        let scene = UIApplication.shared.connectedScenes.first
        if let sceneDelegate = scene?.delegate as? SceneDelegate {  
            if let tabController = sceneDelegate.window?.rootViewController as? UITabBarController {
                  tabController.selectedIndex = 0 // index for menu view conntroller
            }
        }

        // set selected index of the segment control equal to zero


        completionHandler()

    }

这是我的故事板的样子:

我没有试过你的答案,但试试这个

步骤:

最初你需要获取tabbarcontroller的viewcontroller,像这样

 if  let getMenuVC = tabController.viewControllers.first, let getMenu = getMenuVC as? yourMenuController{
  }  

那么你需要获取当前的 class 作为你的 menuviewcontroller

  if let getMenu = getMenuVC as? yourMenuController{
  }  

最后,您需要将当前 class 的段选择索引更新为

   if let getMenu = getMenuVC as? yourMenuController{
         getMenu.yourSegmentedControlName.selectedSegmentIndex = 0
getMenu.yourSegmentedControlName.sendActions(for: UIControl.Event.valueChanged)
      }

最终代码为:

 if let tabController = sceneDelegate.window?.rootViewController as? UITabBarController {
                  tabController.selectedIndex = 0 // index for menu view conntroller
             if  let getMenuVC = tabController.viewControllers?.first, let getMenu = getMenuVC as? yourMenuController{
         getMenu.yourSegmentedControlName.selectedSegmentIndex = 0
getMenu.yourSegmentedControlName.sendActions(for: UIControl.Event.valueChanged)
      }
            }