我想在iOS 11大标题更改时获取该事件。即当它将地点改为&用户滚动视图时从导航栏。我已经检查了UINavigationBar类,但我无法从中获取它。
我要实现的屏幕设计就像大标题可见时我想要透明导航栏但是当标题滚动到导航栏时我想要纯色的导航栏。
答案 0 :(得分:3)
可以通过scrollViewDidScroll func获取UINavigationBar的当前高度来完成。
func scrollViewDidScroll(_ scrollView: UIScrollView) {
//Get current height of navigation bar when tableview/collectionview/scrollview did scroll
guard let navBarHeight = navigationController?.navigationBar.frame.height else {
return
}
//Compare with standard height of navigation bar.
if navBarHeight > 44.0 {
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.barTintColor = .clear
} else {
self.navigationController?.navigationBar.shadowImage = nil
self.navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
self.navigationController?.navigationBar.barTintColor = .green
}
}
答案 1 :(得分:2)
我已将此观察者添加到我的UIViewController子类的ViewWillAppear中。并根据其高度设置颜色如下:
在ViewWillAppear中:
UINavigationBar *navBar = self.navigationController.navigationBar;
[navBar addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew context:nil];
在viewWillDisappear中:
UINavigationBar *navBar = self.navigationController.navigationBar;
[navBar removeObserver:self forKeyPath:@"frame" context:NULL];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
if ([keyPath isEqualToString:@"frame"]) {
[self setNavigationBarColour];;
}
}
- (void)setNavigationBarColour
{
UINavigationBar *navBar = self.navigationController.navigationBar;
CGFloat height = navBar.bounds.size.height;
if(height>44)
{
[navBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
[navBar setTranslucent:YES];
[navBar setShadowImage:[UIImage new]];
}
else
{
[navBar setBackgroundImage:[[UINavigationBar appearance] backgroundImageForBarMetrics:UIBarMetricsDefault] forBarMetrics:UIBarMetricsDefault];
[navBar setTranslucent:NO];
[navBar setShadowImage:[[UINavigationBar appearance] shadowImage]];
}
}
答案 2 :(得分:1)
Piyush Hirpara回答(关于性能)的一个小改进是将您的navigationBar子类化,并且仅在layoutSubviews
上进行更新:
class ObservingLargeTitleNavigationBar: UINavigationBar {
override func layoutSubviews() {
super.layoutSubviews()
updateLargeTitle()
}
private func updateLargeTitle() {
if #available(iOS 11.0, *) {
if frame.height >= 44 {
// code logic when large title is visible
} else {
// code logic when large title is hidden
}
}
}
}
请注意,在某些情况下可能需要调整44
的{{1}}的值。例如,在iPhone X的配置中,我在frame.height
上有它。