Custom UINavigationController UIToolbar Background Image

前端 未结 4 1727
灰色年华
灰色年华 2021-01-30 07:41

I have an iPhone application using UINavigationController and would like to customize the elements with custom background images. I was able to do this for the

4条回答
  •  一向
    一向 (楼主)
    2021-01-30 08:27

    You need to subclass instead of creating a category.

    I'm not too sure why a category works for UINavigationBar but not UIToolbar, but subclassing works for both of them and I think it's the more standard way of customizing stuff like that.

    So to subclass UIToolbar, create a class called MyToolbar (or something similar) and put this in the .h:

    #import 
    #import 
    
    @interface MyToolbar : UIToolbar {}
    
    - (void)drawRect:(CGRect)rect;
    
    @end
    

    And this in the the .m file:

    #import "MyToolbar.h"
    
    @implementation MyToolbar
    
    - (void)drawRect:(CGRect)rect {
        backgroundImage = [UIImage imageNamed:@"my-awesome-toolbar-image.png"];
        [backgroundImage drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    }
    
    @end
    

    From there you've got to tell the Navigation Controller to use MyToolbar instead of UIToolbar. Easiest way I've found to do that is to select your Navigation Controller in Interface Builder, then in the Attributes Inspector check the 'Shows Toolbar' box. The toolbar should show up in the NavigationController window. Click on it and then in the Identity Inspector change the class to MyToolbar.

提交回复
热议问题