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

问题描述 投票:0回答:1

我想在本地通知被打开时显示 "菜单视图控制器"。我在 "菜单视图控制器 "中使用了一个段控制器,当通过本地通知打开视图时,应该将其设置为selectedSegmentIndex=0。我能够打开View Controller,但我不知道如何从app delegate中寻址段控件,这是我使用的代码。

 // 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()

    }

这是我的故事板的样子enter image description here

ios swift xcode appdelegate uisegmentedcontrol
1个回答
0
投票

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

步骤。

最初你需要得到tabbarcontroller的viewcontrollers,像这样的

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

然后你需要得到当前的类作为你的menviewcontroller,比如说

  if let getMenu = getMenuVC as? yourMenuController{
  }  

最后,你需要添加你当前类的段选择索引,如

   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)
      }
            }
© www.soinside.com 2019 - 2024. All rights reserved.