Search code examples
iosobjective-cuiwebviewviewdidloadviewwillappear

Why does adding subview in viewDidLoad doesn't work


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];
}

Solution

  • 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.