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?
Respuesta
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;
}
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.
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;
}
este código no funciona para mí –
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"];
}
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
}
Esto no es 'UITabBarDelegate', es' UITabBarControllerDelegate'. – MoLice
He editado mi respuesta. –
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()
}
}
- 1. Buscar pestaña activa en UITabBarController
- 2. JavaFX TabPane: Cómo establecer la pestaña seleccionada
- 3. WPF TabControl Cambiar la pestaña seleccionada
- 4. Cambiando programáticamente la pestaña seleccionada de tabBarController
- 5. UITabBarController es posible seleccionar la pestaña mediante el código?
- 6. WPF Tab Control: ¿Cómo obtengo la pestaña actualmente seleccionada?
- 7. Qt: ocultar el borde de la pestaña seleccionada en QTabBar
- 8. ¿Cómo obtener la última opción seleccionada de un multiselección?
- 9. Cómo establecer pestaña seleccionada debe estar en medio
- 10. JTabbedPane: acciones realizadas antes de mostrar la pestaña seleccionada
- 11. Jquery UI - ¿volver a cargar la pestaña seleccionada?
- 12. Suprimir másNavigationController en UITabBarController personalizado
- 13. Cambiar a la última pestaña activa en VIM
- 14. ¿Cómo limitar el número de pestañas en un UITabBarController?
- 15. ¿Cómo resaltar la última fila seleccionada después de la clasificación del lado del cliente en jqGrid?
- 16. ¿Hay un evento Cambiado con pestaña seleccionada en el control de pestaña WPF estándar
- 17. Cómo redirigir el asistente de primas a la primera pestaña después de enviar en la última pestaña
- 18. Cómo ocultar uitabbarcontroller
- 19. ¿Cómo ocultar UITabBarController programmatically?
- 20. Necesita identificación de pestaña seleccionada actualmente para las pestañas jQuery
- 21. NERDTree abrir en una nueva pestaña, como última pestaña en gvim?
- 22. Cómo cambiar el color de fondo del color de la pestaña seleccionada de UITabbar a azul?
- 23. ¿Superpone una vista en toda la pantalla cuando usa UITabBarController?
- 24. cómo nombrar la suposición al recordar una expresión?
- 25. jquery click (recordar valor antiguo)
- 26. Programáticos Creación y configuración de UITabBarController - El establecimiento de un sistema de imagen para una pestaña
- 27. ¿Cómo asegurarme de que mi WPF TabControl siempre tiene una pestaña seleccionada cuando contiene al menos una pestaña?
- 28. ¿Es posible cambiar el color de la pestaña seleccionada en Android?
- 29. Cómo cambiar la pestaña seleccionada en el botón hacer clic en WPF TabControl con botones en el encabezado
- 30. ¿Cómo recordar la sesión de múltiples pestañas en la terminal? (Al igual administrador de sesión FF)
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 –