开发者

UITabBarControllerDelegate compare value of viewController

开发者 https://www.devze.com 2022-12-29 08:47 出处:网络
I have a tabBar with 4 tabs on it, and I want to perform some action when a specific tab is selected, so I have 开发者_StackOverflow社区uncommented the UITabBarControllerDelegate in the xxAppDelegate.

I have a tabBar with 4 tabs on it, and I want to perform some action when a specific tab is selected, so I have 开发者_StackOverflow社区uncommented the UITabBarControllerDelegate in the xxAppDelegate.m

I also wanted to see the value that was being sent logged in the console - in order to test my "if" statement. However this is where I got stumped.

// Optional UITabBarControllerDelegate method
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {

    NSLog(@"%@", viewController);
}

The console dutifully logged any selected controller that had been selected, but in this particular format:

<MyViewController: 0x3b12950>

Now, I wasn't expecting the square brackets or the colon or the Hex. So my question is how do I format my IF statement? This is what I thought would work but I get an error mentioned further down.

// Optional UITabBarControllerDelegate method
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {

    NSLog(@"%@", viewController);
    if (viewController == MyViewController)
    {
    //do something nice here …
    };
}

... The error is "Expected expression before 'MyViewController'"

Anyone know how I should be doing this?


You need to compare to a specific view controller instance. For example, if the if statement should be true when the second tab is selected:

if (viewController == [tabBarController.viewControllers objectAtIndex:1]) {
    // ...
}


Thanks that worked. I guess you have to know what object your comparing against first.

For anyone reading this the code supplied works, however you need to be careful that the text "tabBarController" in the example refers to the instance variable (the global one).

In order for your code to work your view controller needs to refer to a uniquely named local version as follows. Compare this to my original code.

// Optional UITabBarControllerDelegate method
- (void)tabBarController:(UITabBarController *)tabBarController_local didSelectViewController:(UIViewController *)viewController 
{
//...
}

Hope this helps someone faced with the

Local declaration of 'tabBarController' hides instance variable 

warning when trying to implement.


When comparing tabbarcontroller use self , like this:

if (viewController == [self.tabBarController.viewControllers objectAtIndex:1]) {
    // ...
}

It will remove the warning.

0

精彩评论

暂无评论...
验证码 换一张
取 消