Как добавить UITabBar в iphone, используя цель c - PullRequest
6 голосов
/ 21 февраля 2011

Как добавить добавить UITabBar программно для приложения iphone. Нужны предложения и пример кода.

Ответы [ 4 ]

28 голосов
/ 06 февраля 2013

Здесь два аспекта ....

Первый аспект ( UITabBarController ): Здесь Вы можете добавить несколько классов (т.е. Viewcontrollers) в UITabBarController, как показано в предыдущих ответах.

Второй аспект ( UITabbar ): здесь Вы можете добавить панель вкладок в любом контроллере представления ... И для этой панели вкладок вы можете добавить несколько элементов UITabBar..и вы можете получить индивидуальныйЭлемент Tabbar Действие .....

См. Код ниже UITabBar

---------> Добавление UITabBar

UITabBar *myTabBar = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
myTabBar.delegate=self;   //here you need import the protocol <UITabBarDelegate>
[self.view addSubview:myTabBar];

---------> Добавление элементов в UITabBar

NSMutableArray *tabBarItems = [[NSMutableArray alloc] init];

UITabBarItem *tabBarItem1 = [[UITabBarItem alloc] initWithTitle:@"Item1" image:[UIImage imageNamed:@"Item1image.png"] tag:0];
UITabBarItem *tabBarItem2 = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemContacts tag:1 ];
UITabBarItem *tabBarItem3 = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemHistory tag:2 ];

[tabBarItems addObject:tabBarItem1];
[tabBarItems addObject:tabBarItem2];
[tabBarItems addObject:tabBarItem3];

myTabBar.items = tabBarItems;
myTabBar.selectedItem = [tabBarItems objectAtIndex:0];

---------> Получение элемента Действия в методе делегата

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
    NSInteger selectedTag = tabBar.selectedItem.tag;
    NSLog(@"%ld",(long)selectedTag);
    if (selectedTag == 0) {
        //Do what ever you want here
    } else if(selectedTag == 1) {
        //Do what ever you want
    } else { //if(selectedTag == 2)
        //Do what ever you want here
    }
}



Обновление: (Swift 2.0)

1. Первый аспект ( UITabBarController ):
Это позволит нам настроить UIViewController s как tabbar элементов в UITabBarController.
Ниже приведенбазовый подход для UITabBarController :

---------> Добавление UITabBarController к окну в appdelegate

let tabBarController = UITabBarController(nibName: nil, bundle: nil)
tabBarController.delegate = self // Need to import 'UITabBarControllerDelegate'
self.window!.rootViewController = tabBarController;
self.window?.makeKeyAndVisible();

---------> Настройка UIViewControllers

let firstViewController = UIViewController()
firstViewController.title = "FirstVC"
firstViewController.tabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.Bookmarks, tag: 0)
let firstNavController: UINavigationController = UINavigationController(rootViewController: firstViewController)

let secondViewController = UIViewController()
secondViewController.title = "SecondVC"
secondViewController.tabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.Contacts, tag: 1)
let secondNavController: UINavigationController = UINavigationController(rootViewController: secondViewController)

let thirdViewController = UIViewController()
thirdViewController.title = "ThirdVC"
thirdViewController.tabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.Downloads, tag: 2)
let thirdNavController: UINavigationController = UINavigationController(rootViewController: thirdViewController)

let forthViewController = UIViewController()
forthViewController.title = "ForthVC"
forthViewController.tabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.Favorites, tag: 3)
let forthNavController: UINavigationController = UINavigationController(rootViewController: forthViewController)

---------> Подключение контроллеров UIView к UITabBarController

tabBarController.viewControllers = [firstNavController, secondNavController, thirdNavController, forthNavController]

---------> Получение события в 'UITabBarControllerDelegate'

func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
    print("didSelectViewController: \(viewController.title) ?")
}


2. Второй аспект ( UITabBar ):
Это позволит нам создавать tabbar предметов.Мы можем получить событие для отдельного элемента в методе делегата
Ниже приведен базовый подход для UITabBar :

---------> Добавление UITabBar к виду

let frame = CGRectMake(0, CGRectGetHeight(self.view.frame) - 49, CGRectGetWidth(self.view.frame), 49)
let tabBar: UITabBar = UITabBar(frame: frame)
tabBar.delegate = self // Need to import 'UITabBarDelegate'
self.view.addSubview(tabBar)

---------> Подготовка TabbarItems

let tabBarItem1 = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.Bookmarks, tag: 0)
let tabBarItem2 = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.Contacts, tag: 1)
let tabBarItem3 = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.Downloads, tag: 2)
let tabBarItem4 = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.Favorites, tag: 3)

--------> Добавление UITabBarItems в UITabBar

tabBar.items = [tabBarItem1, tabBarItem2, tabBarItem3, tabBarItem4]
tabBar.selectedItem = tabBarItem1

---------> Получение события в 'UITabBarDelegate'

func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
    let selectedTag:Int = (tabBar.selectedItem?.tag)!
    print(selectedTag)
    switch selectedTag {
    case 0:
        print("tabBarItem1")
        //Do what ever you want here
    case 1:
        print("tabBarItem2")
        //Do what ever you want here
    case 2:
        print("tabBarItem3")
        //Do what ever you want here
    default:
        print("tabBarItem4")
        //Do what ever you want here
    }
}
7 голосов
/ 21 февраля 2011
- (void) setUpTabBar {
    FirstViewController *firstViewController = [[FirstViewController alloc]init];
    firstViewController.title = @"First View";
    firstViewController.tabBarItem = [[UITabBarItem alloc]initWithTabBarSystemItem:UITabBarSystemItemSearch tag:0];
    UINavigationController *firstNavController = [[UINavigationController alloc]initWithRootViewController:firstViewController];

    SecondViewController *secondViewController = [[SecondViewController alloc]init];
    secondViewController.title = @"Second View";
    secondViewController.tabBarItem = [[UITabBarItem alloc]initWithTabBarSystemItem:UITabBarSystemItemFavorites tag:1];
    UINavigationController *secondNavController = [[UINavigationController alloc]initWithRootViewController:secondViewController];

    ThirdViewController *thirdViewController = [[ThirdViewController alloc]init];
    thirdViewController.title = @"Third View";
    thirdViewController.tabBarItem = [[UITabBarItem alloc]initWithTabBarSystemItem:UITabBarSystemItemRecents tag:2];
    UINavigationController *thirdNavController = [[UINavigationController alloc]initWithRootViewController:thirdViewController];

    ForthViewController *forthViewController = [[ForthViewController alloc]init];
    forthViewController.title = @"Forth View";
    forthViewController.tabBarItem = [[UITabBarItem alloc]initWithTabBarSystemItem:UITabBarSystemItemHistory tag:2];
    UINavigationController *forthNavController = [[UINavigationController alloc]initWithRootViewController:forthViewController];

    tabBarController = [[UITabBarController alloc] initWithNibName:nil bundle:nil];
    tabBarController.viewControllers = [[NSArray alloc] initWithObjects:firstNavController, secondNavController, thirdNavController, forthNavController, nil];
    tabBarController.delegate = self;             
    [self sizeViewToAvailableWindow:[tabBarController view]];

    [firstNavController release];
    [firstViewController release];

    [secondNavController release];
    [secondViewController release];

    [thirdNavController release];
    [thirdViewController release];

    [forthNavController release];
    [forthViewController release];
}

Вот код для программного создания TabBarController.Надеюсь, это поможет вам.

1 голос
/ 21 февраля 2011

вот что вы можете сделать

    SubClassViewController1* vc1 = [[SubClassViewController1 alloc] init];
    UINavigationController* nav1 = [[UINavigationController alloc] initWithRootViewController:vc1];
    nav1.navigationBar.hidden = YES;
    [vc1 release]; vc1 = nil;

    SubClassViewController2* vc2 = [[SubClassViewController2 alloc] init];
    vc2.title = @"List";
    UINavigationController* nav2 = [[UINavigationController alloc] initWithRootViewController:vc2];
    nav2.navigationBar.hidden = YES;
    [vc2 release]; vc2 = nil;

    SubClassViewController3* vc3 = [[SubClassViewController3 alloc] init];
    vc3.title = @"Scan";
    UINavigationController* nav3 = [[UINavigationController alloc] initWithRootViewController:vc3];
    nav3.navigationBar.hidden = YES;
    [vc3 release]; vc3 = nil;

    SubClassViewController4* vc4 = [[SubClassViewController4 alloc] init];
    vc4.title = @"Setting";
    UINavigationController* nav4 = [[UINavigationController alloc] initWithRootViewController:vc4];
    nav4.navigationBar.hidden = YES;
    [vc4 release]; vc4 = nil;

    UITabBarController* tabBar = [[UITabBarController alloc] init];
    [tabBar setViewControllers:[NSArray arrayWithObjects:nav1,nav2,nav3,nav4,nil]];

    [self.navigationController pushViewController:tabBar animated:YES];
    [nav1 release]; nav1 = nil;
    [nav2 release]; nav2 = nil;
    [nav3 release]; nav3 = nil;
    [nav4 release]; nav4 = nil;
    [tabBar release]; tabBar = nil;

Это создаст панель вкладок с четырьмя вкладками и каждой вкладкой со своим собственным viewcontroller и контроллером навигации, то есть каждая вкладка поддерживает свой собственный стек для нажатия и выталкиванияпросмотр контроллера.Я надеюсь, что это помогает U.

0 голосов
/ 10 октября 2012

Вы можете сделать что-то вроде:

UITabBar *tabBar = [[UITabBar alloc] initWithFrame:CGRectMake(0, 430, 320, 50)];
[self.view addSubview:tabBar];

Чтобы добавить некоторые элементы, вы можете написать:

NSMutableArray *tabBarItems = [[NSMutableArray alloc] init];
UITabBarItem *tabBarItem = [[UITabBarItem alloc] initWithTitle:@"Title" image:[UIImage imageNamed:@"Image.png"] tag:0];
UITabBarItem *tabBarItem1 = [[UITabBarItem alloc] initWithTitle:@"Title1" image:[UIImage imageNamed:@"Image1.png"] tag:1];
[tabBarItems addObject:tabBarItem];
[tabBarItems addObject:tabBarItem1];
tabBar.items = tabBarItems;
tabBar.selectedItem = [tabBarItems objectAtIndex:0];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...