Can I give a UIToolBar a custom background in my iPhone app?

后端 未结 10 1000
误落风尘
误落风尘 2020-12-02 09:00

Is it possible to give a UIToolBar a custom background from an image rather than the usual tinted blue/black fade out?

I\'ve tried giving the view a background and s

10条回答
  •  醉酒成梦
    2020-12-02 09:47

    You can do this with a category that basically adds a new property to UIToolBar. Overriding drawRect can work but it's not necessarily future proof. That same strategy for custom UINavigationBar stopped working with iOS 6.

    Here's how I'm doing it.

    .h file

    @interface UIToolbar (CustomToolbar)
    
    @property (nonatomic, strong) UIView *customBackgroundView;
    
    @end
    

    .m file

    #import "CustomToolbar.h"
    #import 
    
    static char TIToolbarCustomBackgroundImage;
    
    @implementation UIToolbar (CustomToolbar)
    
    - (void)setCustomBackgroundView:(UIView *)newView {
        UIView *oldBackgroundView = [self customBackgroundView];
        [oldBackgroundView removeFromSuperview];
    
        [self willChangeValueForKey:@"tfCustomBackgroundView"];
        objc_setAssociatedObject(self, &TIToolbarCustomBackgroundImage,
                                 newView,
                                 OBJC_ASSOCIATION_RETAIN);
        [self didChangeValueForKey:@"tfCustomBackgroundView"];
    
        if (newView != nil) {
            [self addSubview:newView];
        }
    }
    
    - (UIView *)customBackgroundView {
        UIView *customBackgroundView = objc_getAssociatedObject(self, &TIToolbarCustomBackgroundImage);
    
        return customBackgroundView;
    }
    
    @end
    
    

    In your view controller code, e.g. viewDidLoad

        if (self.navigationController.toolbar.customBackgroundView == nil) {
            self.navigationController.toolbar.customBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigation_bar_background.png"]];
            self.navigationController.toolbar.customBackgroundView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        }
    

提交回复
热议问题