Background image for navigation view

2019-01-16 08:47发布

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

alt text

Here is the code:

- (id)initWithStyle:(UITableViewStyle)style {
    if (self = [super initWithStyle:style]) {

        UIImage *image = [UIImage imageNamed: @"bg_table_active.png"];
        UIImageView *imageview = [[UIImageView alloc] initWithImage: image];
        UIBarButtonItem *addButton = [[UIBarButtonItem alloc]
                                       initWithTitle:NSLocalizedString(@"Settings", @"")
                                       style:UIBarButtonItemStyleDone
                                       target:self
                                       action:@selector(GoToSettings)];
        self.navigationItem.titleView = imageview;
        self.navigationItem.rightBarButtonItem = addButton;
        self.navigationItem.hidesBackButton = TRUE;
    }
    return self;
}

How can I make the picture stretch to the whole navigation view?

8条回答
叼着烟拽天下
2楼-- · 2019-01-16 09:19

http://developer.apple.com/iphone/library/featuredarticles/ViewControllerPGforiPhoneOS/UsingNavigationControllers/UsingNavigationControllers.html#//apple_ref/doc/uid/TP40007457-CH7

Looking at Figure 1 in that link - would it be better to set the backgroundImage on your navigationbar not your navigationitem?

查看更多
再贱就再见
3楼-- · 2019-01-16 09:20

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
查看更多
登录 后发表回答