【问题标题】:How do I open the segment index of my segment controller from app delegate?如何从应用程序委托打开我的段控制器的段索引?
【发布时间】:2020-06-02 18:36:29
【问题描述】:

我想在打开本地通知时显示“菜单视图控制器”。我在“菜单视图控制器”中使用了一个段控件,当通过本地通知打开视图时,它应该设置为 selectedSegmentIndex = 0。我能够打开视图控制器,但我不知道如何从应用程序委托解决段控制? 这是我使用的代码:

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

    }

这是我的故事板的外观:

【问题讨论】:

    标签: ios swift xcode appdelegate uisegmentedcontrol


    【解决方案1】:

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

    步骤:

    一开始需要获取tabbarcontroller的viewcontrollers,像这样

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

    那么你需要获取当前类作为你的 menuviewcontroller 就像

      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)
          }
                }
    

    【讨论】:

    • 非常感谢。有用!!!只需在第 3 行的“viewControllers”后面添加一个问号。
    猜你喜欢
    • 2020-09-20
    • 1970-01-01
    • 2015-08-16
    • 2013-10-29
    • 1970-01-01
    • 2022-01-10
    • 2012-12-17
    • 2015-08-22
    • 2011-12-29
    相关资源
    最近更新 更多