Subclassing UIToolbar and overriding drawRect: - UIBarButtonItems NOT displaying

ぃ、小莉子 提交于 2019-12-13 03:09:01

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/16219160/subclassing-uitoolbar-and-overriding-drawrect-uibarbuttonitems-not-displaying

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!