Domanda

Sto cercando di ricordare alla mia app quale ultima scheda è stata visualizzata prima della chiusura dell'app, in modo che l'app si apra alla stessa scheda al prossimo avvio. Questa è la funzionalità della funzione telefono dell'iPhone: come posso farlo?

È stato utile?

Soluzione

Nel delegato di UITabBar, sovrascrivi

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

e memorizza l'indice item in NSUserDefaults. La prossima volta che l'app viene avviata, leggila da lì e ripristina la selezione. Qualcosa del genere:

-prima, imposteresti un delegato per la tua UITabBar, in questo modo:

tabBarController.delegate = anObject;

-in anObject , sovrascrivi didSelectItem :

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

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

          [def synchronize];
        }

Si noti che si salva un NSNumber, poiché i valori int non possono essere serializzati direttamente. Quando avvii di nuovo l'app, leggerà e imposterà il valore selectedIndex dalle impostazioni predefinite:

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

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

   tabBarController.selectedIndex = activeTab;
} 

Altri suggerimenti

Aggiorna

In the UITabBarControllerDelegate's Delegate, overwrite

Obiettivo 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
}

Ho eseguito la sottoclasse di 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"];
}

Ecco come l'ho fatto. Entrambi i metodi sono in appDelegate e tabBarController è una variabile di istanza.

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

Ecco la soluzione Swift 3. Basta impostare la classe del TabBarController su RememberingTabBarController nello 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()
    }
}

Memorizza l'indice di tabulazione selezionato nelle preferenze NSUserDefaults ogni volta che l'utente seleziona una nuova scheda. Quindi, quando l'app viene riavviata, carica quel valore dalle preferenze e seleziona manualmente quella scheda.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top