UITabBarController не может установить выбранную вкладку из быстрого действия для дополнительных вкладок при запуске приложения

У меня есть приложение, которое использует UITabBarController с 7 вкладками. Каждая вкладка является подклассом UIViewController (каждый встроен в UINavigationController), который просто имеет другой цвет фона в наборе представлений в раскадровке. Элементы TabIms помечены как Tab 1 - Tab 7, а заголовок, установленный в каждом NavBar, представляет собой просто номер Tab. Я добавил несколько статичных быстрых действий в свой Info.plist, которые позволяют мне переходить на вкладки 2, 3, 6 и 7.

Проблема, с которой я сталкиваюсь, заключается в том, что когда я устанавливаю выбранную вкладку при обработке быстрого действия в AppDelegate, все отлично работает для первых 4 вкладок. Если я выберу одну из вкладок, перечисленных в списке "Больше...", приложение откроется только при выборе первой вкладки в моем UITabBarController. Однако, если приложение уже запущено, и я перехожу на домашний экран и снова пытаюсь выполнить быстрые действия, оно может выбрать любую вкладку из списка "Дополнительно". Есть идеи?

Вот мой код AppDelegate:

//  AppDelegate.swift

import UIKit

@UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate 
{

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        // handle quick actions
        if let shortcutItem =
        launchOptions?[UIApplicationLaunchOptionsKey.shortcutItem]
            as? UIApplicationShortcutItem {

            let _ = handleShortcut(shortcutItem: shortcutItem)
            return false
        }

        return true
    }

    func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {

        completionHandler(handleShortcut(shortcutItem: shortcutItem))
    }

    private func handleShortcut(shortcutItem: UIApplicationShortcutItem) -> Bool {
        let shortcutType = shortcutItem.type
        guard let shortcutIdentifier = ShortcutIdentifier(fullIdentifier: shortcutType) else {
            return false
        }

        switch shortcutIdentifier {
        case ShortcutIdentifier.OpenTab2: fallthrough
        case ShortcutIdentifier.OpenTab3: fallthrough
        case ShortcutIdentifier.OpenTab6: fallthrough
        case ShortcutIdentifier.OpenTab7:
            return selectTabBarItem(forIdentifier: shortcutIdentifier)
        }
    }

    private func selectTabBarItem(forIdentifier identifier: ShortcutIdentifier) -> Bool {
        if let tabBarController = self.window?.rootViewController as? CustomTabBarController
        {

            switch (identifier)
            {
            case .OpenTab2:
                tabBarController.selectedIndex = tabDictionary["OpenTab2"]!
            case .OpenTab3:
                tabBarController.selectedIndex = tabDictionary["OpenTab3"]!
            case .OpenTab6:
                tabBarController.selectedIndex = tabDictionary["OpenTab6"]!
            case .OpenTab7:
                tabBarController.selectedIndex = tabDictionary["OpenTab7"]!
            }
        }
        return true
    }

    // Integer in dictionary denotes tab number (zero based)
    private let tabDictionary = ["OpenTab2": 1, "OpenTab3": 2, "OpenTab6": 5, "OpenTab7": 6]

    enum ShortcutIdentifier: String {
        case OpenTab2
        case OpenTab3
        case OpenTab6
        case OpenTab7

        init?(fullIdentifier: String) {
            guard let shortIdentifier = fullIdentifier.components(separatedBy: ".").last else {
                return nil
            }
            self.init(rawValue: shortIdentifier)
        }
    }

}

1 ответ

Я нашел следующую ссылку ( http://jakzaprogramowac.pl/pytanie/18417,select-index-greater-than-3-for-uitabbarcontroller-at-app-launch-not-working), которая, казалось, отвечала на мой вопрос. Я надеюсь, что это помогает другим.

Я добавил следующий код в начало AppDelegate DidFinishLaunchingWithOptions, чтобы изначально выбрать первую вкладку и вызвать layoutIfNeeded() в представлении tabBarController:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool 
{
    // Override point for customization after application launch.

    // initially select first tab so more selection works from quick    actions - fixup
    if let tabBarController = self.window?.rootViewController as? CustomTabBarController
    {
        tabBarController.selectedIndex = 0
        tabBarController.view.layoutIfNeeded()
    }

    // handle quick actions
    if let shortcutItem =
    launchOptions?[UIApplicationLaunchOptionsKey.shortcutItem]
        as? UIApplicationShortcutItem {

        let _ = handleShortcut(shortcutItem: shortcutItem)
        return false
    }

    return true
}        
Другие вопросы по тегам