0

Context

I'm using the 'initWithNavigationBarClass' method to initialize a UINavigationController with a custom toolbar, here is the line where I alloc init the UINavigationController

navigationController = [[UINavigationController alloc] initWithNavigationBarClass:nil toolbarClass:[QuestionToolbar class]];

Is the class, "QuestionToolbar", I subclass UIToolbar and override drawrect, here is the drawRect method:

    - (void)drawRect:(CGRect)rect
    {
      [super drawRect:rect];
      UIImage *backgroundImage = [UIImage imageNamed:@"44px_background_red.png"];
      [backgroundImage drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    }

Here is pertinent code in the viewController where I attempt to add the UIBarButtonItems

UIBarButtonItem *spacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *beginItem = [[UIBarButtonItem alloc] initWithTitle:@"Begin Quiz" style:UIBarButtonItemStylePlain target:self action:@selector(beginAction:)];

[beginItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIColor whiteColor], UITextAttributeTextColor,nil] forState:UIControlStateNormal];

NSArray *items = [NSArray arrayWithObjects:spacer, beginItem, spacer, nil];
[self.navigationController.toolbar setItems:items];

[self.navigationController setToolbarHidden:NO];

Problem

How do I go about adding UIBarButtonItems to this toolbar as they don't show-up when I try to add them?

I assume it's something to do with my overriding drawRect

drc
  • 1,905
  • 4
  • 22
  • 28
  • I think I figured this out, I was using this code: [self.navigationController.toolbar setItems:items] which didn't work. But if I used self.toolbarItems = items it worked. Not sure why? – drc Apr 25 '13 at 17:23

1 Answers1

0

I tried myself with a custom UIToolbar and the problem is not from -(void)drawRect:(CGCrect)rect.

I don't know wehere do you try to add the buttons on the UIToolbar but you should try to add them in -(void)viewDidAppear method of your UIViewController class. In this way it worked for me.

danypata
  • 9,895
  • 1
  • 31
  • 44
  • Thanks for your answer danypata, see my comment from earlier I changed to using self.toolbarItems instead of self.navigationController.toolbar setItems:item and this fixed it. Any idea why? – drc Apr 25 '13 at 18:16
  • So basically the Apple Docs states that the navigation controller `obtains its current set of items from the toolbarItems property of the active view controller`. So basically the right way to set toolbarItems is via UIViewController.toolbarItems property. – danypata Apr 26 '13 at 06:57
  • @I don't believe this is correct see: http://stackoverflow.com/questions/16228275/uibutton-hidden-behind-uitoolbar – drc Apr 26 '13 at 20:32