3

I was trying to add UIToolBar into a UIWebView but whenever I insert this code inside viewDidLoad UIToolBar doesn't show up, however when this is done in viewWillAppear, it works. Can someone please explain it to me.

-(void)viewDidLoad
{
[super viewDidLoad];
self.forwardButton = [[UIBarButtonItem alloc]initWithTitle:@"Forward"          style:UIBarButtonItemStylePlain target:self action:@selector(forward)];
self.backButton = [[UIBarButtonItem alloc]initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:self action:@selector(back)];
NSArray *buttonsArray = @[self.backButton,self.forwardButton];
CGRect toolBarFrame = CGRectMake(0, self.view.frame.size.height - 44, self.view.frame.size.width, 44);
self.toolbar = [[UIToolbar alloc]initWithFrame:toolBarFrame];
[self.toolbar setItems:buttonsArray animated:YES];
[self.toolbar sizeToFit];
[self.view addSubview:self.toolbar];
}
user3526002
  • 537
  • 2
  • 8
  • 19
  • seems like storyboard to me but anyways... to clear things up, check similar questions: [Unable to set frame correctly before viewDidAppear](http://stackoverflow.com/q/13079172/2857130) or [UIViewController returns invalid frame?](http://stackoverflow.com/q/9539676/2857130) – staticVoidMan May 17 '14 at 11:14

1 Answers1

6

Add subview in viewDidLoad, but set its frame in viewWillAppear. self.view.frame is being set just before viewWillAppear is called by UIKit. The value you get in viewDidLoad is the one was set in nib and is often different from the actual frame.

Don't forget to set autoresizingMask or use auto layout.

Sash Zats
  • 5,376
  • 2
  • 28
  • 42
  • is bounds set before the frame then? – user3526002 May 19 '14 at 01:50
  • 2
    UIKit sets correct dimensions just prior to `viewWillAppear:` meaning that `frame`, `bounds` and `center` will be set. All these properties are backed by the same attributes of corresponding `CALayer` so, unless `transform` is set you should expect similar behavior from both `frame` and `bounds` in terms of "correctness". Hope it makes sense. – Sash Zats May 19 '14 at 07:02