Custom background for UINavigationBar problems

后端 未结 5 1481
清酒与你
清酒与你 2020-12-29 17:13

I\'ve managed to add a custom background to my navigation bar by using:

UIImageView *iv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@\"UINavigat         


        
5条回答
  •  执笔经年
    2020-12-29 17:57

    Instead of doing it in drawRect: you can override the drawLayer:inContext: method in a UINavigationBar category class. Inside the drawLayer:inContext: method, you can draw the background image you want to use. Also you can choose different images for portrait and landscape interface orientations if your app supports multiple interface orientations.

    - (void) drawLayer:(CALayer *)layer inContext:(CGContextRef)context
    {
        if ([self isMemberOfClass:[UINavigationBar class]] == NO) {
            return;
        }
    
        UIImage *image = (self.frame.size.width > 320) ?
                            [UINavigationBar bgImageLandscape] : [UINavigationBar bgImagePortrait];
        CGContextClip(context);
        CGContextTranslateCTM(context, 0, image.size.height);
        CGContextScaleCTM(context, 1.0, -1.0);
        CGContextDrawImage(context, CGRectMake(0, 0, self.frame.size.width, self.frame.size.height), image.CGImage);
    }
    

    This complete demo Xcode project on customizing the appearance of UINavigationBar might also be helpful.

提交回复
热议问题