开发者

How to override the drawRect method in UINavigationBar dynamically?

I have a static UINavigationBar for most of my app but toward the end I have a few view controllers that need the background image set dynamically based on some property in the view controller itself.

The code I currently have to set this works fine, except the dynamic part. Is it possible to override the drawRect method at runtime to set the background image dynamically?

@implementation UINavigationBar (UINavigationBarCategory)
- (void)drawRect:(CGRect)rect {
  UIColor *color = [UIColor blackColor];
    UIImage *img    = [UIImage imageNamed: @"nav.png"];
    [img drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height开发者_JS百科)];
    self.tintColor = color;
}
@end


Overriding methods with categories is a wrong thing to do, even though it works in this particular case.

If you have the navigation controller instantiated in a NIB, you can subclass UINavigationBar and set the navigation controller's bar class to your own one in Interface Builder. Once you do that, you have much more control over the navigation bar's appearance.

@interface MyNavigationBar : UINavigationBar
{
    UIImage* customImage;
}
@property(nonatomic,retain) UIImage* customImage;
@end

@implementation MyNavigationBar
-(void)drawRect:(CGRect)rect
{
    if (self.customImage) {
        // draw your own image
    } else {
        [super drawRect:rect];
    }
}
@end

Remember to make the "customized" view controllers reset the customImage property to nil in viewWillDisappear:.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜