Pergunta

Eu estou tentando fazer meu aplicativo lembrar qual guia foi último a ser visto antes do aplicativo parar, de modo que o aplicativo se abre para a mesma guia quando está próxima lançado. Esta é a funcionalidade da função de telefone do iPhone: como posso fazer isso

?
Foi útil?

Solução

Em Delegado do UITabBar, sobrescrever

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item

e armazenar 's índice de item na NSUserDefaults. Da próxima vez que seu aplicativo é iniciado, lê-lo de lá, e configurá-lo de volta para ser selecionado. Algo parecido com isto:

-primeiro, você deve definir um delegado para seu UITabBar, como este:

tabBarController.delegate = anObject;

-in anObject , de substituição didSelectItem :

       - (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
        {
          NSUserDefaults *def = [NSUserDefaults standardUserDefaults];

          [def setInteger: [NSNumber numberWithInt: tabBarController.selectedIndex]
 forKey:@"activeTab"];

          [def synchronize];
        }

Note que você salvar um NSNumber, como int valores podem não ser serializado diretamente. Quando você iniciar o aplicativo novamente, ele irá ler e definir o selectedIndex valor dos padrões:

- (void)applicationDidFinishLaunchingUIApplication *)application {  
   NSUserDefaults *def = [NSUserDefaults standardUserDefaults];

   int activeTab = [(NSNumber*)[def objectForKey:@"activeTab"] intValue];

   tabBarController.selectedIndex = activeTab;
} 

Outras dicas

Atualizar

In the UITabBarControllerDelegate's Delegate, overwrite

Objective C

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
NSLog(@"%lu",self.tabBarController.selectedIndex);
return YES;
}

In this delegate method you will get last selected index.

Swift 3.2

func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool
{
    print("%i",tabBarController.selectedIndex)
    return true
}

Eu subclasse TabBarController e:

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.selectedIndex = [[NSUserDefaults standardUserDefaults] integerForKey:@"activeTab"];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    [[NSUserDefaults standardUserDefaults] setInteger: self.selectedIndex
             forKey:@"activeTab"];
}

Aqui está como eu fiz isso. Ambos os métodos são na appDelegate e tabBarController é uma variável de instância.

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */

    //Remember the users last tab selection
    NSInteger tabIndex = self.tabBarController.selectedIndex;
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setInteger: tabIndex forKey:@"activeTab"];

    if (![userDefaults synchronize]) 
    {
        NSLog(@"Error Synchronizing NSUserDefaults");
    }

}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */

    //Set the tabBarController to the last visted tab
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    int activeTab = [(NSNumber*)[userDefaults objectForKey:@"activeTab"] intValue];
    self.tabBarController.selectedIndex = activeTab;
}

Aqui está a solução Swift 3. Basta definir a classe do seu TabBarController para RememberingTabBarController no Storyboard

import Foundation
import UIKit

class RememberingTabBarController: UITabBarController, UITabBarControllerDelegate {
    let selectedTabIndexKey = "selectedTabIndex"

    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate = self

        // Load the last selected tab if the key exists in the UserDefaults
        if UserDefaults.standard.object(forKey: self.selectedTabIndexKey) != nil {
            self.selectedIndex = UserDefaults.standard.integer(forKey: self.selectedTabIndexKey)
        }
    }

    func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        // Save the selected index to the UserDefaults
        UserDefaults.standard.set(self.selectedIndex, forKey: self.selectedTabIndexKey)
        UserDefaults.standard.synchronize()
    }
}

armazenar o índice guia selecionada nas preferências NSUserDefaults cada vez que o usuário seleciona uma nova guia. Em seguida, quando o aplicativo começa a voltar-se, a carga que o valor das preferências e selecionar manualmente que guia.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top