Background image for navigation view

前端 未结 8 1810
小鲜肉
小鲜肉 2020-12-07 17:17

I am having problems with properly displaying background image of navigation view. Here is the pic:

相关标签:
8条回答
  • Mike Rundle and Casebash's code is great. I used [NSValue valueWithNonretainedObject:self] to avoid the copyWithZone error. Wrapping self in an NSValue object allows it to be copied into the navigationBarImages dictionary.

    
    - (void)drawRect:(CGRect)rect
    {
        NSString *imageName=[navigationBarImages objectForKey:[NSValue valueWithNonretainedObject:self]];
    ...}
    

    
    - (void)setImage:(NSString*)image
    {
        [navigationBarImages setObject:image forKey:[NSValue valueWithNonretainedObject:self]];
    }
    

    0 讨论(0)
  • 2020-12-07 17:59

    I modified Mike Rundle's version so that the a custom image can be set if necessary. I also merged in 40lb-suit-of-bees suggested changes. initImageDictionary needs to be called during initialisation:

    //UINavigationBar+CustomImage.h
    #import <Foundation/Foundation.h>
    
    @interface UINavigationBar(CustomImage)
    + (void) initImageDictionary;
    - (void) drawRect:(CGRect)rect;
    - (void) setImage:(UIImage*)image;
    @end
    
    
    //UINavigationBar+CustomImage.m    
    #import "UINavigationBar+CustomImage.h"
    //Global dictionary for recording background image
    static NSMutableDictionary *navigationBarImages = NULL;
    
    @implementation UINavigationBar(CustomImage)
    //Overrider to draw a custom image
    
    + (void)initImageDictionary
    {
        if(navigationBarImages==NULL){
            navigationBarImages=[[NSMutableDictionary alloc] init];
        }   
    }
    
    - (void)drawRect:(CGRect)rect
    {
        NSString *imageName=[navigationBarImages objectForKey:[NSValue valueWithNonretainedObject: self]];
        if (imageName==nil) {
            imageName=@"header_bg.png";
        }
        UIImage *image = [UIImage imageNamed: imageName];
        [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    }
    
    //Allow the setting of an image for the navigation bar
    - (void)setImage:(UIImage*)image
    {
        [navigationBarImages setObject:image forKey:[NSValue valueWithNonretainedObject: self]];
    }
    @end
    
    0 讨论(0)
提交回复
热议问题