Programing

프로그래밍 방식으로 TabBar 탭보기로 전환 하시겠습니까?

lottogame 2020. 6. 9. 07:37
반응형

프로그래밍 방식으로 TabBar 탭보기로 전환 하시겠습니까?


UIButtoniPhone 앱에 하나의 탭보기가 있고의 탭 막대에서 다른 탭을 열고 싶다고 가정 해 봅시다 TabBarController. 이를 위해 코드를 어떻게 작성합니까?

기존보기를 언로드하고 특정 탭보기를로드한다고 가정하지만 코드를 정확하게 작성하는 방법을 모르겠습니다.


Swift 또는 Objective-C에서이 코드를 사용해보십시오.

빠른

self.tabBarController.selectedIndex = 1

목표 -C

[self.tabBarController setSelectedIndex:1];

탭은 0부터 시작하여 색인화됩니다. 따라서 다음 코드 스 니펫이 작동합니다.

tabBarController = [[UITabBarController alloc] init];
.
.
.
tabBarController.selectedViewController = [tabBarController.viewControllers objectAtIndex:4];

막대의 다섯 번째 탭으로 이동합니다.


내 의견이다 selectedIndex또는 사용이 objectAtIndex탭을 전환 할 수있는 가장 좋은 방법은 필요하지 않습니다. 탭을 재정렬하면 하드 코딩 된 인덱스 선택으로 인해 이전 앱 동작이 엉망이 될 수 있습니다.

전환하려는 뷰 컨트롤러의 객체 참조가있는 경우 다음을 수행 할 수 있습니다.

tabBarController.selectedViewController = myViewController

물론 반드시 myViewController의 목록에 있는지 확인해야합니다 tabBarController.viewControllers.


selectedIndexUITabBarController 속성을 적절한 인덱스로 설정하기 만하면 사용자가 탭 버튼을 탭한 것처럼보기가 변경됩니다.


나는 Disco S2가 제안한 것을 시도했지만 가까이 있었지만 이것이 나를 위해 일한 결과입니다. 다른 탭 내에서 작업을 완료 한 후 호출되었습니다.

for (UINavigationController *controller in self.tabBarController.viewControllers)
{
    if ([controller isKindOfClass:[MyViewController class]])
    {
        [self.tabBarController setSelectedViewController:controller];
        break;
    }
}

탭을 이동할 수있는 경우 코드는 다음과 같습니다.

for ( UINavigationController *controller in self.tabBarController.viewControllers ) {
            if ( [[controller.childViewControllers objectAtIndex:0] isKindOfClass:[MyViewController class]]) {
                [self.tabBarController setSelectedViewController:controller];
                break;
            }
        }

IB를 연결하는 방법에 덜 의존하는 강력한 솔루션을 생각하면서 인덱스 대신 클래스별로 표시되는 탭을 지정할 수 있기를 원했습니다. Disco 또는 Joped의 솔루션이 작동하지 않아서이 방법을 만들었습니다.

-(void)setTab:(Class)class{
    int i = 0;
    for (UINavigationController *controller in self.tabBarContontroller.viewControllers){
        if ([controller isKindOfClass:class]){
            break;
        }
        i++;
    }
    self.tabBarContontroller.selectedIndex = i;
}

당신은 이것을 다음과 같이 부릅니다.

[self setTab:[YourClass class]];

이것이 누군가에게 도움이되기를 바랍니다.


Stuart Clark의 솔루션과 같지만 Swift 3의 경우 :

func setTab<T>(_ myClass: T.Type) {
    var i: Int = 0
    if let controllers = self.tabBarController?.viewControllers {
        for controller in controllers {
            if let nav = controller as? UINavigationController, nav.topViewController is T {
                break
            }
            i = i+1
        }
    }
    self.tabBarController?.selectedIndex = i
}

Use it like this:

setTab(MyViewController.self)

Please note that my tabController links to viewControllers behind navigationControllers. Without navigationControllers it would look like this:

if let controller is T {

My issue is a little different, I need to switch from one childViewController in 1st tabBar to home viewController of 2nd tabBar. I simply use the solution provided in the upstairs:

tabBarController.selectedIndex = 2

However when it switched to the home page of 2nd tabBar, the content is invisible. And when I debug, viewDidAppear, viewWillAppear, viewDidLoad, none of them is called. My solutions is to add the following code in the UITabBarController:

override var shouldAutomaticallyForwardAppearanceMethods: Bool 
{
    return true
}

Use in AppDelegate.m file:

(void)tabBarController:(UITabBarController *)tabBarController
 didSelectViewController:(UIViewController *)viewController
{

     NSLog(@"Selected index: %d", tabBarController.selectedIndex);

    if (viewController == tabBarController.moreNavigationController)
    {
        tabBarController.moreNavigationController.delegate = self;
    }

    NSUInteger selectedIndex = tabBarController.selectedIndex;

    switch (selectedIndex) {

        case 0:
            NSLog(@"click me %u",self.tabBarController.selectedIndex);
            break;
        case 1:
            NSLog(@"click me again!! %u",self.tabBarController.selectedIndex);
            break;

        default:
            break;

    }

}

Like Stuart Clark's solution but for Swift 3 and using restoration identifier to find correct tab:

private func setTabById(id: String) {
  var i: Int = 0
  if let controllers = self.tabBarController?.viewControllers {
    for controller in controllers {
      if let nav = controller as? UINavigationController, nav.topViewController?.restorationIdentifier == id {
        break
      }
      i = i+1
    }
  }
  self.tabBarController?.selectedIndex = i
}

Use it like this ("Humans" and "Robots" must also be set in storyboard for specific viewController and it's Restoration ID, or use Storyboard ID and check "use storyboard ID" as restoration ID):

struct Tabs {
    static let Humans = "Humans"
    static let Robots = "Robots"
}
setTabById(id: Tabs.Robots)

Please note that my tabController links to viewControllers behind navigationControllers. Without navigationControllers it would look like this:

if controller.restorationIdentifier == id {

import UIKit

class TabbarViewController: UITabBarController,UITabBarControllerDelegate {

//MARK:- View Life Cycle

override func viewDidLoad() {
    super.viewDidLoad()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}

//Tabbar delegate method
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    let yourView = self.viewControllers![self.selectedIndex] as! UINavigationController
    yourView.popToRootViewController(animated:false)
}



}

참고URL : https://stackoverflow.com/questions/5413538/switching-to-a-tabbar-tab-view-programmatically

반응형