自定义 UINavigationBar 在顶部偏移 1 个像素

Posted

技术标签:

【中文标题】自定义 UINavigationBar 在顶部偏移 1 个像素【英文标题】:Custom UINavigationBar is offset by 1 pixel at the top 【发布时间】:2012-04-12 21:32:08 【问题描述】:

我有一个子类 UINavigationBar,我在其中覆盖 drawRect 以提供具有透明度的 png 作为背景。一切都按预期工作,除了栏顶部的 1 像素空间(我可以看到底层地图在空间中移动)。

screen shot

我唯一能找到的是这个听起来像我的问题但我不知道该怎么解释的问题:Empty space of 1 pixel above UINavigationBar

我已验证 PNG 文件在图像顶部没有 1 像素的透明度。 在子类 UINavigationBar 中覆盖:

- (void)drawRect:(CGRect)rect  

[_bg drawInRect:CGRectMake(0, 0, _bg.size.width, _bg.size.height)];
// showing correct bounds - drawRect: 0.000000, 0.000000, 320.000000, 85.000000
NSLog(@"drawRect: %f, %f, %f, %f",  rect.origin.x, 
                                    rect.origin.y, 
                                    rect.size.width, 
                                    rect.size.height);

- (CGSize)sizeThatFits:(CGSize)size 
CGRect frame = [[UIScreen mainScreen] applicationFrame];
CGSize sz = CGSizeMake(frame.size.width, _bg.size.height);
NSLog(@"sizefits");
return sz;

感谢您的帮助!

【问题讨论】:

您使用的是 24/32 位的 png 图像还是 8 位的? 您好,谢谢您的回复。我双重验证,它是 32 位的。有什么想法吗? 【参考方案1】:

虽然我使用 UIAppearance 代理来设置自定义背景图像而不是覆盖 drawRect:,但我的自定义导航栏也遇到了同样的问题。这是我在根视图控制器上的 viewWillAppear: 中的快速修复:

// Make sure nav bar is flush with status bar (ios 5 iPhone portrait somehow gives status bar height 20 and nav bar y 20.5, so we miss a pixel).
CGRect navBarFrame = self.navigationController.navigationBar.frame;
navBarFrame.origin.y = [UIApplication sharedApplication].statusBarFrame.size.height;
self.navigationController.navigationBar.frame = navBarFrame;

【讨论】:

以上是关于自定义 UINavigationBar 在顶部偏移 1 个像素的主要内容,如果未能解决你的问题,请参考以下文章

iOS 11 - Navigationbar 大标题自定义偏移

创建此自定义 UINavigationbar ios 的最佳方法

删除大标题 UINavigationBar 中 UISearchController 顶部的 1px 行

自定义导航栏高度

UINavigationViewController中的UITableView偏移,显示在UINavigationBar下

如何在 UINavigationBar 上设置自定义按钮?