To get myself back into the swing of coding, I decided to write a simple application for iOS devices. I figured this would be a good way to learn the most up to date practices and re-familiarize myself with the iOS SDK. This would also help me get use to the nuances of Objective-C again.
The application I was writing was based on the UITabBar class. This worked well with the way the application was going to work and I figured it would be simple enough that there would be a lot of examples out there on the internet. I assumed correctly for the most part with the exception being how to make the application change tabs from a button on the view rather than the tabs on the tab bar.
When I googled for the solution there were a lot of results with different ways to do it. Most of the ones that I found said to use the navigationController and it’s pushViewController method. An example:
[self.navigationController pushViewController:lvc animated:YES];
I tried it using the proper names of the controllers for my application and it compiled without any errors. Unfortunately when I tried to run it the view didn’t change as expected. It did absolutely nothing.
As I looked into it further it seemed as if those examples were adding a navigationController on top of the tabbarController. I didn’t understand exactly why they were doing it but maybe it just fit their application design. I thought about adding it in to see if I could make it work, but my application really had no need for a separate navigationController. So I continued to look for the solution to my problem.
So after a while I found the solution. You just have to reference the tabBarController of your view and use the setSelectedIndex. It looks like this:
[[self tabBarController] setSelectedIndex:1];
One warning though when doing this, make sure that you remember the index count is like an array. Your first view will be at index 0. Then your second view will be at index 1. So on and so forth. You get the point.
It was such a simple solution and I’m sure I could have easily found it had I just looked through the class reference documentation. Unfortunately I get impatient and just figured google would have the answer a lot faster. That’s what I get for trying to take the “easy way” out. I figured I would add this to my blog just in case anyone else has trouble trying to find the solution for this.