由于swift中属性初始化可以在定义的时候就写初始化代码,而OC中初始化自定义属性的代码需要写进init方法里面:
_customBar = [[UINavigationBar alloc]initWithFrame: CGRectMake(0, 0, [UIScreen cz_screenWidth], 64)];
_customItem = [[UINavigationItem alloc]init];
原本题主只需要写上这两句代码,但是画蛇添足了就是把设置自定义navigationBar的方法全放这里面去了。结果问题来了:
错误示例:
- (void)viewDidLoad {
[super viewDidLoad];
[self setupUI];
}
/**
重写init方法,以便同时初始化自定义属性
@return self
*/
- (instancetype)init
{
self = [super init];
if (self) {
[self setupNavigationBar];
}
return self;
}
- (void)setupUI {
self.view.backgroundColor = [UIColor cz_randomColor];
}
/**
重写设置title方法
@param title 标题
*/
- (void)setTitle:(NSString *)title {
[super setTitle:title];
_customItem.title = title;
}
/**
设置自定义Bar和Item
*/
- (void)setupNavigationBar {
_customBar = [[UINavigationBar alloc]initWithFrame: CGRectMake(0, 0, [UIScreen cz_screenWidth], 64)];
_customItem = [[UINavigationItem alloc]init];
_customBar.items = @[_customItem];
_customBar.barTintColor = [UIColor cz_colorWithHex:0xF6f6f6];
[self.view addSubview:_customBar];
}
先说说结果吧,结果就是push 出来的类在下方代码里怎么都获取不到self.navigationController.
- (void)viewDidLoad {
[super viewDidLoad];
self.title = [NSString stringWithFormat: @"第%d个",self.navigationController.childViewControllers.count];
}
however
同样的类下,在另一个按钮监听方法里却可以正常获取到self.navigationController.
[self.navigationController pushViewController:vc animated:YES];
总之觉得非常的奇怪,然后将代码恢复到之前的样子,发现又没有问题了。调试了一会儿之后,发现问题就出现在这句代码上:
[self.view addSubview:_customBar];
在init的时候,只要我加上了这句代码,就会有问题。在push出来的类中viewDidLoad方法获取不到self.navigationController.
最后
希望题主发现的问题能帮到因为这个问题困惑到的朋友,还有就是希望是否有知道的朋友能告诉我这是什么原因?