tags:

views:

809

answers:

1

I am creating a view controller programmatically which is a UITabBarDelegate and contains a UITabBar.

UITabBar *tabBar = [[UITabBar alloc] initWithFrame:CGRectMake(0, 200, 320, 49)];
[self.view addSubview:tabBar];

I don't really want to hardcode the frame values in case the screen resolution changes or I use the view in a different context with a different height, for example.

I'm vaguely aware I can create the tab bar without these values and probe the window and tabbar for height and width to calculate the desired values but I'm struggling to achieve this. What I want to achieve is a tab bar of the standard width and height correctly positioned at the bottom of the enclosing view.

A: 

Maybe something like this:

UITabBar *tabBar = [[UITabBar alloc] init]; //init with default width and height
tabBar.frame = CGRectMake(0,
                          self.view.frame.size.height - tabBar.frame.size.height,
                          self.view.frame.size.width,
                          tabBar.frame.size.height)]; //place it at the bottom of the view
[self.view addSubview:tabBar];
[tabBar release];

EDIT:

I've realised thet the size of a newly instantiated UITabBar is zero. Probably your best bet is to use a UITabBarController, as it already sizes your UITabBar accordingly:

UITabBarController *tabBarController = [[UITabBarController alloc] init];
[self.view addSubview: tabBarController.view];
luvieere
This is very similar to what I've been trying before, but for some reason the values returned from self.view.frame.size.height or width are all (null)?
andybee
That's curious :-? Try self.view.bounds.size.width and height
luvieere
NSLog(@"%@", tabBar); returns '<UITabBar: 0x3d203e0; frame = (0 0; 320 49); layer = <CALayer: 0x3d20720>>', but tabBar.frame or tabBar.bounds return (null). Same goes for self.view.frame or self.view.bounds? I take it this is unexpected behaviour so I should probably pop this out to a new question?
andybee
How do you write the NSLog statement for tabBar.frame ? Try a *NSLog(@"%d", tabBar.frame.size.height);* What do you get?
luvieere
I get the value 0 but I guess this is because we're forcing it to a decimal, if it's a string %@ I get '(null)'.
andybee
Well, we are not "forcing" it, the *tabBar.frame.size.height* **is** a decimal, not a string.
luvieere
I understand that, but if we specify %d and the value is NULL rather than an integer value, it will evaluate to 0?
andybee
You are right, the size of the newly instantiated UITabBar is zero. Probably your best bet is to use a UITabBarController, as it already sizes your UITabBar accordingly.
luvieere
I was trying to avoid this as I'm pushing this 'TabbedViewController' on to a Navigation Controller. I am considering revisiting my application flow logic to avoid this situation.
andybee
for tabBar.frame.size.height we have to use %f , height is in CGFloat
RVN