且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

更改每个导航上的导航栏背景图像

更新时间:2021-12-17 22:21:09

CustomNavigation.h

CustomNavigation.h

    #import <Foundation/Foundation.h>


    @interface UINavigationBar (UINavigationBarCustomDraw){

    }

    @end

CustomNavigation.m

CustomNavigation.m

    @implementation UINavigationBar (UINavigationBarCustomDraw)

    - (void) drawRect:(CGRect)rect {

        [self setTintColor:[UIColor colorWithRed:0.5f
                                           green: 0.5f
                                            blue:0 
                                           alpha:1]];

        if ([self.topItem.title length] > 0) {


            if ([self.topItem.title isEqualToString:@"First"]) {

                [[UIImage imageNamed:@"First.png"] drawInRect:rect];

            }

            else if ([self.topItem.title isEqualToString:@"Second"]) {

                [[UIImage imageNamed:@"Second.png"] drawInRect:rect];                   

            }




            CGRect frame = CGRectMake(0, 0, 320, 44);
            UILabel *label = [[[UILabel alloc] initWithFrame:frame] autorelease];
            [label setBackgroundColor:[UIColor clearColor]];
            label.font = [UIFont boldSystemFontOfSize: 20.0];
            label.shadowColor = [UIColor colorWithWhite:0.0 alpha:1];
            label.textAlignment = UITextAlignmentCenter;
            label.textColor = [UIColor whiteColor];
            label.text = self.topItem.title;
            self.topItem.titleView = label;





        } 


        else {
            [[UIImage imageNamed:@"wood.png"] drawInRect:rect];
            self.topItem.titleView = [[[UIView alloc] init] autorelease];
        }



    }

    @end

如果你想用 First.png 在 FirstViewController 中设置 navigationBar 背景图片 那么

if u want to First.png to set navigationBar background image in FirstViewController then

在你的 FirstViewController.m 中

in ur FirstViewController.m

        -(void) viewWillAppear:(BOOL)animated{

        [super viewWillAppear:animated];



            self.title=@"First";
            [self.navigationController.navigationBar drawRect:CGRectMake(0, 0, 320, 480)];

    }

如果你想通过 Second.png 在 SecondViewController 中设置 navigationBar 背景图片,那么

if u want to Second.png to set navigationBar background image in SecondViewController then

在你的 SecondViewController.m 中

in ur SecondViewController.m

        -(void) viewWillAppear:(BOOL)animated{

        [super viewWillAppear:animated];



            self.title=@"Second";
            [self.navigationController.navigationBar drawRect:CGRectMake(0, 0, 320, 480)];

    }