Добавление контроллера панели вкладок программно в текущий поток приложений - программирование
Подтвердить что ты не робот

Добавление контроллера панели вкладок программно в текущий поток приложений

Я хочу добавить вкладку Bar Controller в мой текущий поток приложений. В настоящее время у меня есть страница с кнопкой, которая при нажатии открывает новый viewcontroller с веб-представлением, где пользователь входит в систему и после входа в систему, я хочу забрать его на свою домашнюю страницу, где панель навигации имеет свое имя и кнопка выхода вправо, На домашней странице также должна быть панель вкладок с 3 различными вкладками. Я могу загрузить представление домашней страницы из webview и получить панель навигации. Но я не могу добавить tabBar и заставить его работать. Я смущен относительно того, где добавить код для добавления TabBar. Я использую приведенный ниже код, чтобы добавить панель вкладок -

UITabBarController *tabBar = [[UITabBarController alloc] init];

HomeViewController *home = [[PPHomeViewController alloc] initWithUserName:[self.userInfo objectForKey:@"name"] Email:[self.userInfo objectForKey:@"email"] Phone:[self.userInfo objectForKey:@"phone_number"]];
home.tabBarItem = [[UITabBarItem alloc]initWithTabBarSystemItem:UITabBarSystemItemFavorites tag:1];
UINavigationController *homeNavController = [[UINavigationController alloc]initWithRootViewController:home];

RequestViewController *req = [[RequestMoneyViewController alloc]init];
req.tabBarItem = [[UITabBarItem alloc]initWithTabBarSystemItem:UITabBarSystemItemFavorites tag:2];
UINavigationController *reqNavController = [[UINavigationController alloc]initWithRootViewController:req];

UIViewController *thirdViewController = [[UIViewController alloc]init];
thirdViewController.tabBarItem = [[UITabBarItem alloc]initWithTabBarSystemItem:UITabBarSystemItemFavorites tag:3];
UINavigationController *thirdNavController = [[UINavigationController alloc]initWithRootViewController:thirdViewController];

UIViewController *fourthViewController = [[UIViewController alloc]init];
thirdViewController.tabBarItem = [[UITabBarItem alloc]initWithTabBarSystemItem:UITabBarSystemItemFavorites tag:3];
UINavigationController *fourthNavController = [[UINavigationController alloc]initWithRootViewController:fourthViewController];

tabBar.viewControllers = [[NSArray alloc] initWithObjects:homeNavController, reqNavController, thirdNavController, fourthNavController, nil];
tabBar.delegate=self;
tabBar.selectedIndex=0;

UIImageView *homeImg=[[UIImageView alloc]initWithFrame:CGRectMake(0, 432, 80, 49)];
homeImg.tag=11;
homeImg.image=[UIImage imageNamed:@"footer"];

UIImageView *reqImg=[[UIImageView alloc]initWithFrame:CGRectMake(81, 432,80, 49)];
reqImg.tag=12;
reqImg.image=[UIImage imageNamed:@"footer"];

UIImageView *sendImg=[[UIImageView alloc]initWithFrame:CGRectMake(162, 432,80, 49)];
sendImg.tag=13;
sendImg.image=[UIImage imageNamed:@"footer"];

UIImageView *localImg=[[UIImageView alloc]initWithFrame:CGRectMake(243, 432, 80, 49)];
localImg.tag=14;
localImg.image=[UIImage imageNamed:@"footer"];

[tabBar.view addSubview:homeImg];
[tabBar.view addSubview:reqImg];
[tabBar.view addSubview:sendImg];
[tabBar.view addSubview:localImg];

[[[UIApplication sharedApplication]keyWindow]addSubview:tabBar.view];

В настоящее время я поставил вышеуказанный код в viewDidLoad ViewController TabViewController, который расширяет UITabBarController. В моем контроллере webView я поставил следующий код -

TabViewController *tab=[[TabViewController alloc] init];
tab.userInfo=userInfo;
[self presentViewController:tab animated:YES completion:nil];

Но приложение падает, как только я нажимаю любую вкладку, отличную от той, которая уже открыта. Пожалуйста, помогите.

4b9b3361

Ответ 1

То, как я это делал в прошлом, - создать подкласс UITabBarController, содержащий весь код создания tabBar, который вы указали выше.

Затем используйте UINavigationController для подталкивания подкласса tabBar к экрану.

Здесь образец моего подкласса UITabBarController:

- (void)viewDidLoad {
    [super viewDidLoad];

    UIViewController *view1 = [[UIViewController alloc] init];
    UIViewController *view2 = [[UIViewController alloc] init];
    UIViewController *view3 = [[UIViewController alloc] init];

    NSMutableArray *tabViewControllers = [[NSMutableArray alloc] init];
    [tabViewControllers addObject:view1];
    [tabViewControllers addObject:view2];
    [tabViewControllers addObject:view3];

    [self setViewControllers:tabViewControllers];
    //can't set this until after its added to the tab bar
    view1.tabBarItem = 
      [[UITabBarItem alloc] initWithTitle:@"view1" 
                                    image:[UIImage imageNamed:@"view1"] 
                                      tag:1];
    view2.tabBarItem = 
      [[UITabBarItem alloc] initWithTitle:@"view2" 
                                    image:[UIImage imageNamed:@"view3"] 
                                      tag:2];
    view3.tabBarItem = 
      [[UITabBarItem alloc] initWithTitle:@"view3" 
                                    image:[UIImage imageNamed:@"view3"] 
                                      tag:3];      
}

Ответ 2

Установить делегат UITabBarDelegate

здесь Изображение TabBar Viewcontroller   http://prntscr.com/ba5oks

#pragma mark- Tapbar delegate

- (void)deselectTabBarItem:(UITabBar*)tabBar
{
    tabBar.selectedItem = nil;
}

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
    [self performSelector:@selector(deselectTabBarItem:) withObject:tabBar afterDelay:0.2];

    switch (item.tag) {
        case 0:
            //perform action
            break;
        case 1:
            //do whatever you want to do.
            break;
        case 2:
            //call method
            break;
        default:
            break;
    }
}