为什么这不起作用?我想订阅 UINavigationBar,所以在 xcode 中我单击新文件 -> 目标 c 类,类: 自定义导航栏子类: 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,但我觉得它不如订阅它那么正确。在我的第一个视图的视图中DidLoad,我添加了这一行:
- (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];
}
}
我同意Ryan Perry的观点。除了他的回答:
你不应该把这段代码放在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!!
}
根据 initWithFrame 的文档:
如果使用界面生成器设计界面,则在随后从 nib 文件加载视图对象时不会调用此方法。nib 文件中的对象被重构,然后使用其 initWithCoder: 方法进行初始化,该方法修改视图的属性以匹配存储在 nib 文件中的属性。有关如何从 nib 文件加载视图的详细信息,请参阅资源编程指南。
http://developer.apple.com/library/ios/#documentation/uikit/reference/uiview_class/uiview/uiview.html
这就是该方法未按预期调用的原因。
必须使用initWithCoder:
方法,因为从情节提要加载 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;
}
您可以按如下方式对 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