How to use the same [Storyboard] view for multiple tabs, and just change little things about it depending on the tab selected? (iOS)

StackOverflow https://stackoverflow.com/questions/17766240

سؤال

I know this question is worded kind of strangely, but let me explain what I'm trying to do:

Let's say that I have an app with 2 tabs, each with their own view. Both views are almost exactly the same, except one contains a button or two that the other one doesn't, and vice versa.

I already made one view in Storyboard mode, now I want to change just a little tiny bit about it and reuse the same view for the other tab.

I don't want to do a deep copy, because if I change one, then I would have to change the other, and that might cause some inconsistency between the two.

So how should I go about using the same generic view for multiple tabs, and just change little things about it depending on which tab I am in?

Should I add the universal content in storyboard view, and then programmatically add the particular tab-exclusive content? If I did this, I would need a way to detect what tab is selected, right? Is there a way to do that?

Thank you for any suggestions!

هل كانت مفيدة؟

المحلول

You don't need a Storyboard for that. Sure you can drag a view in there and assign it to a specific class and program all stuff in that, but if you really need only one view in there the storyboard is useless. You should deal with subviews programmatically if you want to change something. This is very good and you have great features like animationWithDuration:

For checking which Tab in your UITabBarController is selected you can use self.tabBarController.selectedIndex and compare it with the given Index of the Tab which is selected.

EDIT:

If we assume you have a green Button on Tab with index 0, and the same Button should slide a little bit above and a red Button should appear where green Button when Tab with index 1 is tapped.

UIButton *greenButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 320, 100, 20)];
    greenButton.backgroundColor = [UIColor greenColor];
    [self.view addSubview:greenButton];


    UIButton *redButton = [[UIButton alloc] initWithFrame:CGRectMake(0, greenButton.frame.origin.y, 100, 20)];
    greenButton.backgroundColor = [UIColor redColor];

    if (self.tabBarController.selectedIndex == 1) {
        [UIView animateWithDuration:1.0 animations:^{
            greenButton.frame = CGRectMake(0, 300, 100, 20);
        } completion:^(BOOL finished) {
            [self.view addSubview:redButton];
        }];
    }

First you create the two buttons and add the green one to the view. (The first view is at index 0). Then you check if the selectedIndex is 1 and animate the Buttons around.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top