¿Cómo recordar la última pestaña seleccionada en UITabBarController?
Pregunta
Estoy tratando de hacer que mi aplicación recuerde qué pestaña se vio por última vez antes de que se cierre la aplicación, de modo que la aplicación se abra en la misma pestaña cuando se lance la próxima vez. Esta es la funcionalidad de la función del teléfono del iPhone: ¿cómo puedo hacer esto?
Solución
En el delegado de UITabBar, sobrescribir
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
y almacenar el índice de elemento en NSUserDefaults. La próxima vez que se inicie su aplicación, léala desde allí y vuelva a configurarla para que se seleccione. Algo como esto:
-primero, establecería un delegado para su UITabBar, así:
tabBarController.delegate = anObject;
-en unObjeto , sobrescriba 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, ya que los valores int no se pueden serializar directamente. Cuando vuelva a iniciar la aplicación, leerá y establecerá el valor selectedIndex de los valores predeterminados:
- (void)applicationDidFinishLaunchingUIApplication *)application {
NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
int activeTab = [(NSNumber*)[def objectForKey:@"activeTab"] intValue];
tabBarController.selectedIndex = activeTab;
}
Otros consejos
UPDATE
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
}
Subclasifiqué TabBarController y:
- (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"];
}
Así es como lo hice. Ambos métodos están en appDelegate 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;
}
Aquí está la solución Swift 3. Simplemente configure la clase de su TabBarController en 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()
}
}
Almacene el índice de pestaña seleccionado en las preferencias de NSUserDefaults cada vez que el usuario seleccione una pestaña nueva. Luego, cuando la aplicación se inicie nuevamente, cargue ese valor desde las preferencias y seleccione manualmente esa pestaña.