2016-11-06 3 views
2

Я создал пользовательский UITabBarController с 5 вкладками в Swift 3.0. Я пытаюсь установить различные элементы навигационной панели для определенных вкладок, но это не работает.Swift: настройка различных кнопок панели навигации для разных вкладок

Ситуация: Я поместил коды, которые изменят кнопки панели навигации в представлении каждой вкладкиDidLoad().

//The customized Tab Bar controller instance. Contained in each of the tabs. 
var mainController: TabBarController? 

override func viewDidLoad() { 
    // ... more code 
    setupNavBar() 
    // ... more code 
} 

func setupNavBar() { 
    // ... more code 
    mainController?.navigationItem.leftBarButtonItem = UIBarButtonItem(image: friendsImage, style: .plain, target: self, action: #selector(handleFindFriends)) 
    // ... more code 
} 

Проблема: Скажем Tab # 1 должен иметь NavBarButton А и Tab # 2 должен иметь NavBarButton B. Когда я переключаюсь с Tab # 1 к закладке № 2, код работает отлично; NavBarButton изменяется от A до B. Однако, когда я нажимаю Tab Tab 1, NavBarButton по-прежнему остается B.

Как это сделать, чтобы кнопки панели навигации менялись соответственно, даже когда я нажимаю на вкладку I был ранее?

+1

Пусть зделать TabBarController и (NavigationController> ViewController) для каждой вкладки. Таким образом, вы можете добавить barButtonItem для каждого ViewController. –

+0

Я добавил код к моему ответу, пожалуйста, взгляните. –

ответ

1

Я на самом деле нашел XD решение В TabBarController:

override func viewWillAppear(_ animated: Bool) { 
    //Original code to set up tabs 

    //Code I added: 
    for i in 0...4 { 
     tabBar.items?[i].tag = i 
    } 
} 
//Code I added: 
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) { 
    //Code to run when a certain tab is selected 
} 

Тем не менее, спасибо большое!

2

Я предполагаю, что вы вставляете UITabBarController (или его подкласс) в UIViewController. Это неправильно, потому что в этом случае вы, как правило, создаете общий контроллер представления, который обычно является плохой практикой.

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

enter image description here

UPDATE

Если вы делаете это в коде:

@UIApplicationMain 
class AppDelegate: UIResponder, UIApplicationDelegate { 

    var window: UIWindow? 


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 

     let tabBarController = UITabBarController() 

     // first tab 
     let firstViewController = UIViewController() 
     _ = firstViewController.view 
     firstViewController.title = "First" 
     let firstNavigationController = UINavigationController(rootViewController: firstViewController) 

     // sets a specific button ("Friends") on a navigation bar for the first screen 
     firstViewController.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Friends", style: .plain, target: nil, action: nil) 

     // second tab 
     let secondViewController = UIViewController() 
     _ = secondViewController.view 
     secondViewController.title = "Second" 
     let secondNavigationController = UINavigationController(rootViewController: secondViewController) 

     // sets a specific button ("Photos") on a navigation bar for the second screen 
     secondViewController.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Photos", style: .plain, target: nil, action: nil) 

     // embeds the navigation controllers into the tab bar controller 
     tabBarController.viewControllers = [firstNavigationController, secondNavigationController] 

     // creates a window with the tab bar controller inside 
     window = UIWindow(frame: UIScreen.main.bounds) 
     window?.rootViewController = tabBarController 
     window?.makeKeyAndVisible() 

     return true 
    } 

} 
+0

Вот образ моего ответа, хорошая работа @ Артем Степаненко – emresancaktar

Смежные вопросы