How to Get the Selected Tab in CPTabBarTemplate When Clicking a Tab in CarPlay?

Hi everyone,

I'm developing a CarPlay application and using a CPTabBarTemplate to display multiple tabs. I want to determine which tab is selected when the user clicks on a tab, specifically when switching to the second tab.

Here’s the relevant part of my code:

class CarPlaySceneDelegate: UIResponder, CPTemplateApplicationSceneDelegate {
    var interfaceController: CPInterfaceController?
    var tabBarTemplate: CPTabBarTemplate = CPTabBarTemplate(templates: [])
    
    func templateApplicationScene(
        _ templateApplicationScene: CPTemplateApplicationScene,
        didConnect interfaceController: CPInterfaceController
    ) {
        self.interfaceController = interfaceController

        // Create and set the TabBarTemplate
        let tabBarTemplate = createTabBarTemplate()
        self.tabBarTemplate = tabBarTemplate

        interfaceController.setRootTemplate(tabBarTemplate, animated: false) { success, error in
            if let error = error {
                print("Error setting TabBarTemplate: \(error.localizedDescription)")
            } else {
                print("TabBarTemplate set successfully.")
            }
        }
    }

    func createTabBarTemplate() -> CPTabBarTemplate {
        let listItem1 = CPListItem(text: "Item 1", detailText: "Detail 1")
        let listItem2 = CPListItem(text: "Item 2", detailText: "Detail 2")
        let listTemplate = CPListTemplate(
            title: "List",
            sections: [CPListSection(items: [listItem1, listItem2])]
        )

        let gridButton1 = CPGridButton(
            titleVariants: ["Grid 1"],
            image: UIImage(systemName: "star.fill")!
        )
        let gridButton2 = CPGridButton(
            titleVariants: ["Grid 2"],
            image: UIImage(systemName: "star")!
        )
        let gridTemplate = CPGridTemplate(
            title: "Grid",
            gridButtons: [gridButton1, gridButton2]
        )

        return CPTabBarTemplate(templates: [listTemplate, gridTemplate])
    }
}
Answered by Frameworks Engineer in 817970022

Hello, your app needs to assign a delegate to the tab bar template and implement the tabBarTemplate:didSelectTemplate: method in that delegate object. That will notify your app each the time user selects a tab in your app.

Hello, your app needs to assign a delegate to the tab bar template and implement the tabBarTemplate:didSelectTemplate: method in that delegate object. That will notify your app each the time user selects a tab in your app.

How to Get the Selected Tab in CPTabBarTemplate When Clicking a Tab in CarPlay?
 
 
Q