Custom navigation bar

前端 未结 6 474
故里飘歌
故里飘歌 2021-01-30 03:19

I was crawling Dribble and found the attached design. I was wondering how to do a custom navigation bar like this. I mean how create the navigation bar once and reuse it implici

6条回答
  •  不思量自难忘°
    2021-01-30 03:58

    In older iOS versions you have to subclass UINavigationBar i.e.:

    @interface CustomNavigationBar : UINavigationBar
    @end
    
    @implementation CustomNavigationBar
    
    - (id)initWithCoder:(NSCoder *)aDecoder {
        self = [super initWithCoder:aDecoder];
        if (self) {
            self.opaque = YES;
            self.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"CustomBackground"]];
        }
        return self;
    }
    
    - (void)drawRect:(CGRect)rect {
        // Skip standard bar drawing
    }
    
    @end
    

    To use a custom navigation bar in your view controller, you should change a standard class name to CustomNavigationBar in XIB.

    Also, you can set the custom navigation bar programmatically:

    UIViewController *tempController = [[[UIViewController alloc] init] autorelease];
    UINavigationController *navigationController = [[[UINavigationController alloc] initWithRootViewController:tempController] autorelease];
    
    NSData *archive = [NSKeyedArchiver archivedDataWithRootObject:navigationController];
    NSKeyedUnarchiver *unarchiver = [[[NSKeyedUnarchiver alloc] initForReadingWithData:archive] autorelease];
    [unarchiver setClass:[CustomNavigationBar class] forClassName:@"UINavigationBar"];
    UINavigationController *customNavigationController = [unarchiver decodeObjectForKey:@"root"];
    
    UIViewController *contentController = [[[ContentViewController alloc] init] autorelease];
    customNavigationController.viewControllers = [NSArray arrayWithObject:contentController];
    

    Now customNavigationController has the custom navigation bar.

提交回复
热议问题