Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tab bar with multiple tabs using only one view controller

I was not able to find an answer to my problem on SO, please link me if an answer already exists somewhere! My problem seems pretty common- i have a tableview embedded in a nav controller and i want a tab bar with 3 items, where the 3 items change the tableview to populate different data, the first tab representing the default data in the tableview when the view is loaded.

But it seems unnecessary to make two extra UITableViewController classes for the other two tabs, when i can simply just change the data populating the table, with a simple [tableView reloadData]. How do you go about doing this, and also how to implement this in storyboard?

like image 275
VeganKid Avatar asked Mar 18 '23 23:03

VeganKid


2 Answers

Sounds to me what you really want is a single UITableViewController with a Segmented Control to change the view.Tab Bars are for navigation.

Segmented Control

Use UIControlEventValueChanged to detect the change, load the new data and reload the view.

You didn't indicate what you mean by 'different data'. If you mean something like perform some action which updates data via a CoreData fetch/predicate/sort, etc. then using the Segmented Control is probably the way to go. If your data is dramatically different (different entities, different data management, etc. ) then you should probably go with separate UITableViewControllers as you should not try to over generalize your UITableViewController but rather pair your data to your UITableViewController. After all, that's what it is for.

like image 104
Wizkid Avatar answered Apr 06 '23 05:04

Wizkid


You can make multiple relationship segue to one controller with ctrl+drag like this.

storyboard> 5 times ctrl+drag to one Navigation Controller

And you should make CustomTabBarController.swift to modify tabs. Don't forget to change class name of TabBarController that is drawn in storyboard.

class CustomTabBarController: UITabBarController {
    let MENUS = ["tab1", "tab2", "tab3", "tab4", "tab5"]

    override func viewDidLoad() {
        super.viewDidLoad()

        let items = tabBar.items!

        for (var idx=0; idx<items.count; idx++) {
            items[idx].title = MENUS[idx]
            items[idx].tag = idx
        }
    }
...
}

You can use tag or selected index of tabs on the ViewController.swift

let tag = self.tabBarController?.tabBar.selectedItem!.tag

let selectedIndex = self.tabController?.selectedIndex
like image 45
hoi Avatar answered Apr 06 '23 07:04

hoi