简体   繁体   中英

Custom back button disappears after setting navigation bar background image

I'm using the following categories code to change the background image of the navigation bar

#import <Foundation/Foundation.h>

@interface UINavigationBar (CustomImage)
- (void) setBackgroundImage:(UIImage*)image;
- (void) clearBackgroundImage;
@end


#import "UINavigationBar+CustomImage.h"

@implementation UINavigationBar (CustomImage)
- (void) setBackgroundImage:(UIImage*)image {
    if (image == NULL) return;
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    imageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    [self insertSubview:imageView atIndex:0];
    [imageView release];
}

- (void) clearBackgroundImage {    
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSArray *mySubviews = [self subviews];

    for (int i = [mySubviews count] - 1; i >= 0; i--)
    {
        if ([[mySubviews objectAtIndex:i] isMemberOfClass:[UIImageView class]])
        {
            [[mySubviews objectAtIndex:i] removeFromSuperview];
            return;
        }
    }

    [pool release];
}
@end

And i'm using the following code to generate the custom back button in my view

UIButton *btnBack = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
[btnBack addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
[btnBack setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
UIBarButtonItem *barBtnBack = [[UIBarButtonItem alloc] initWithCustomView:btnBack];
self.navigationItem.leftBarButtonItem = barBtnBack;

[btnBack release];
[barBtnBack release];

But the button most of the time is hidden under the bg image and some times it randomly appears. Why is this happening? I'm not sure what's the problem the image is inserted at index 0 so as I understand it is supposed to be behind all the time. Please help.

添加图像后,您应该尝试创建按钮。

Try the following code to change background of the navigation bar in the class where you are loading the navigation bar.

@interface UINavigationBar (MyCustomNavBar)
@end
@implementation UINavigationBar (MyCustomNavBar)
- (void) drawRect:(CGRect)rect 
{
    UIImage *barImage = [UIImage imageNamed:@"image.png" ];
    [barImage drawInRect:rect];
}
@end

使用Praveen S方法建议您可以为下一个背景图像名称设置一个全局变量,并在viewDidLoad方法中进行设置,然后在draw rect方法中使用存储在变量中的imageName而不是对其进行硬编码。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM