Daniel Wang Daniel Wang - 1 year ago 128
iOS Question

How to add KVO for UINavigationBar hidden/unhidden?

I'm trying to add an observer for

UINavigationBar
hidden/unhidden like the following code, but it does not work anyway:

[self.navigationController addObserver:self forKeyPath:@"navigationBarHidden" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];


and also tried this,still not work:

[self.navigationController.navigationBar addObserver:self forKeyPath:@"hidden" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];


when I check the
self.navigationController.navigationBar
in LLDB,it told me property
navigationController not found for UIViewController
(means
self
). Does anyone have the same problem?

addtional message:

- (void)viewDidLoad {
[self.navigationController.navigationBar addObserver:self forKeyPath:@"hidden" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];


}

- (void)dealloc {
[self.navigationController.navigationBar removeObserver:self forKeyPath:@"hidden"];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
if ([keyPath isEqualToString:@"hidden"]) {
NSLog(@"navigation bar is hidden/unhidden");
}
}


I tried for navigationBarHidden and hidden both.

Answer Source

KVO operates only on properties that are set using KVC. UINavigationController has no KVC-compliant property pertaining to the showing and hiding of its navigation bar. Therefore you cannot use KVO to detect when the navigation bar is shown and hidden.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download