2012-12-12 48 views
0

为什么这不起作用?我想sublcass UINavigationBar的所以在Xcode我点击新的文件 - >目标C类, 类:CustomNavBar 子类:UINavigationBar的iOS:如何继承UINavigationBar

导航控制器的场景下的故事板

然后,我点击导航栏,并设置它的类到CustomNavBar。

然后我进入我的CustomNaVBar类并尝试添加自定义图像背景。

在initWithFram方法我已经加入这个:

- (id)initWithFrame:(CGRect)frame 
{ 
    NSLog(@"Does it get here?"); //no 
    self = [super initWithFrame:frame]; 
    if (self) { 
     // Initialization code 
     UIImage *image = [UIImage imageNamed:@"customNavBarImage.png"]; 
     // [self setBackgroundImage:image forBarMetrics:UIBarMetricsDefault]; 
     [self setBackgroundColor:[UIColor colorWithPatternImage:image]]; 
     [[UINavigationBar appearance] setBackgroundImage:image forBarMetrics:UIBarMetricsDefault]; 
     NSLog(@"Does this get called?"); //no 
    } 
    return self; 
} 

我没有看到在控制台上的任何输出。

相反,我已经这样做了自定义UINavBar,但我觉得它不像子分类那样正确。在我的第一个观点的viewDidLoad我加入这一行:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]) { 
     UIImage *image = [UIImage imageNamed:@"customNavBarImage.png"]; 
     [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault]; 
    } 
} 
+0

在'init'方法或'layoutSubviews'方法中添加该方法。它应该工作。 – iDev

+0

那么,我总是只使用viewDidLoad。似乎子类化对于设置背景图像来说相当有用。 – Josiah

回答

2

我同意瑞恩佩里。除了他的回答:

你不应该把这个代码initWithFrame,而不是把你的代码中awakeFromNib

- (void) awakeFromNib { 
    // Initialization code 
    UIImage *image = [UIImage imageNamed:@"customNavBarImage.png"]; 
    // [self setBackgroundImage:image forBarMetrics:UIBarMetricsDefault]; 
    [self setBackgroundColor:[UIColor colorWithPatternImage:image]]; 
    [[UINavigationBar appearance] setBackgroundImage:image forBarMetrics:UIBarMetricsDefault]; 
    NSLog(@"Does this get called?"); //YES!! 
} 
1

根据对initWithFrame的文档:

如果您使用Interface Builder来设计自己的界面,这种方法是叫当你的看法对象随后从nib文件加载。 nib文件中的对象被重构,然后使用其initWithCoder:方法进行初始化,该方法修改视图的属性以匹配存储在nib文件中的属性。有关如何从nib文件加载视图的详细信息,请参阅资源编程指南。

http://developer.apple.com/library/ios/#documentation/uikit/reference/uiview_class/uiview/uiview.html

这将是该方法不歌厅叫像你期望它的原因。

0

你也可以继承的UINavigation条如下:

@interface CustomNavigationBar : UINavigationBar 

@end 

@implementation CustomNavigationBar 

- (void)drawRect:(CGRect)rect 
{  
    //custom draw code 
} 

@end 

//Begin of UINavigationBar background customization 
@implementation UINavigationBar (CustomImage) 

//for iOS 5 
+ (Class)class { 
    return NSClassFromString(@"CustomNavigationBar"); 
} 

@end 
1

你必须使用initWithCoder:方法,因为从Storyboard加载UI对象时,它是指定的初始化程序。因此,使用此代码:

- (id)initWithCoder:(NSCoder *)aDecoder 
{ 
    NSLog(@"Does it get here?"); // now it does! 
    self = [super initWithCoder:aDecoder]; 
    if (self) { 
     // Initialization code 
     // ... 
     NSLog(@"Does this get called?"); // yep it does! 
    } 
    return self; 
}