UitabbarController에서 마지막으로 선택된 탭을 기억하는 방법은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/1623234

  •  06-07-2019
  •  | 
  •  

문제

앱이 종료되기 전에 마지막으로 보는 탭을 기억하려고 앱을 기억하려고합니다. 따라서 다음에 출시 될 때 앱이 동일한 탭으로 열리도록합니다. 이것이 iPhone의 전화 기능의 기능입니다. 어떻게해야합니까?

도움이 되었습니까?

해결책

Uitabbar의 대의원에서 덮어 쓰십시오

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

그리고 저장 안건nsuserDefaults의 색인. 다음에 앱이 시작될 때 앱을 읽고 읽고 다시 선택하십시오. 이 같은:

-첫 번째, 당신은 다음과 같은 Uitabbar 대의원을 설정합니다.

tabBarController.delegate = anObject;

-안에 객체, 덮어 쓰기 didSelectEM:

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

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

          [def synchronize];
        }

nsnumber를 저장합니다 int 값은 직접 직렬화 될 수 없습니다. 앱을 다시 시작하면 읽고 설정합니다. 선택된 index 기본값의 값 :

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

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

   tabBarController.selectedIndex = activeTab;
} 

다른 팁

업데이트

In the UITabBarControllerDelegate's Delegate, overwrite

객관적인 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.

스위프트 3.2

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

나는 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"];
}

내가 한 방법은 다음과 같습니다. 두 방법 모두 AppDelegate에 있으며 TabBarController는 인스턴스 변수입니다.

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

Swift 3 솔루션은 다음과 같습니다. TabbarController의 클래스를 설정하기 만하면됩니다 RememberingTabBarController 스토리 보드에서

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

사용자가 새 탭을 선택할 때마다 NSUSERDEFAULTS 환경 설정에 선택한 탭 색인을 저장하십시오. 그런 다음 앱이 다시 시작되면 환경 설정에서 해당 값을로드하고 해당 탭을 수동으로 선택하십시오.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top