2009-10-26 7 views
10

Estoy tratando de hacer que mi aplicación recuerde qué pestaña se estaba viendo por última vez antes de que la aplicación se cierre, de modo que la aplicación abra la misma pestaña cuando se lance de nuevo. Esta es la funcionalidad de la función del teléfono del iPhone: ¿cómo puedo hacer esto?¿Cómo recordar la última pestaña seleccionada en UITabBarController?

+0

Echa un vistazo a esta pregunta reciente, también: http://stackoverflow.com/questions/1619478/how-can-i-have-my- iphone-app-start-with-a-specific-screen-showing –

Respuesta

6

En Delegado del UITabBar, sobrescribir

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

y almacenar índice de elemento 's en NSUserDefaults. La próxima vez que inicie su aplicación, léala desde allí y vuelva a configurarla para que sea seleccionada. Algo como esto:

-primero, se establecería un delegado para su UITabBar, así:

tabBarController.delegate = anObject; 

-en unObjeto, sobrescribir didSelectItem:

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

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

      [def synchronize]; 
     } 

Tenga en cuenta que guarda un NSNumber, como int, los valores no se pueden serializar directamente. Al iniciar la aplicación de nuevo, se leerá y establecer el valorselectedIndex de los valores predeterminados:

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

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

    tabBarController.selectedIndex = activeTab; 
} 
+0

@luvieere Lo siento, pero ¿puede elaborar con un poco más de código de muestra, por favor? – quantum

+0

Claro, acabo de hacer eso. – luvieere

+0

@luvieere Ooops, estableces NSNumber en lugar de Int – Shmidt

0

Almacene el índice de pestañas seleccionado en las preferencias de NSUserDefaults cada vez que el usuario seleccione una pestaña nueva. Luego, cuando la aplicación vuelva a iniciarse, cargue ese valor de las preferencias y seleccione manualmente esa pestaña.

1

Así es como lo hice. Ambos métodos están en la aplicaciónDelegate y tabBarController es una variable de instancia.

- (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; 
} 
+0

este código no funciona para mí –

2

I subclases y tabBarController:

- (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"]; 
} 
5

ACTUALIZACIÓN

In the UITabBarControllerDelegate's Delegate, overwrite 

Objetivo 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 
} 
+0

Esto no es 'UITabBarDelegate', es' UITabBarControllerDelegate'. – MoLice

+0

He editado mi respuesta. –

0

Aquí está la solución Swift 3. Sólo hay que establecer la clase de su tabBarController a RememberingTabBarController en el 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() 
    } 
} 
Cuestiones relacionadas