2017-07-31 106 views
0

我想为UINavigationBar设置一个背景图像。在Objective-C中我做了很多次,但很快,我面临一个问题。我搜查了很多东西,但都没有为我工作。UINavigatoinBar背景图像出现两次swift

这里是我使用的代码:

let navBackgroundImage:UIImage! = UIImage(named: "header") 
self.navigationController?.navigationBar.setBackgroundImage(navBackgroundImage, for: .default) 

我的标题图片已经以下尺寸:

375×64,用于1x和等用于2x和3次。我也尝试过使用320x64,但仍然无法正常工作。

截图:

enter image description here 正如你所看到的图像出现两次,而不是覆盖整个宽度。

有什么建议吗?

编辑

尝试后

self.navigationController?.navigationBar.setBackgroundImage(UIImage(named: "header")?.resizableImage(withCapInsets: UIEdgeInsetsMake(0, 0, 0, 0), resizingMode: .stretch), for: .default) 

enter image description here 仍然会出现两次。

+0

检查此链接:https://stackoverflow.com/questions/26052454/ios-8-navigat ionbar-backgroundimage – 3stud1ant3

+0

我没有看到任何问题在上面的背景图像设置导航栏的方式。内部应该对图像进行相应的拉伸和显示。你为什么不尝试设置一些其他图像,因为它可能与你尝试的图像有一些问题? – Shreekara

回答

1

试试这个,

斯威夫特

self.navigationController?.navigationBar.setBackgroundImage(UIImage(named: "header")?.resizableImage(withCapInsets: UIEdgeInsetsMake(0, 0, 0, 0), resizingMode: .stretch), for: .default) 

目标C

[self.navigationController.navigationBar setBackgroundImage:[[UIImage imageNamed:@"header"] resizableImageWithCapInsets: UIEdgeInsetsMake(0, 0, 0, 0) resizingMode: UIImageResizingModeStretch] forBarMetrics:UIBarMetricsDefault]; 
+0

我试过了,但仍然是,导航栏图像出现两次,如截图。 – iBug

+0

您是否删除了以前的代码?因为屏幕截图中有两个图像 –

+0

是的,我的代码仅被调用一次,这是我设置背景图像的唯一位置。 – iBug

0

尝试打印的东西,或使用调试点确保您的代码不叫两次,或使用

let navBackgroundImage:UIImage! = UIImage(named: "header")!.resizableImage(withCapInsets: UIEdgeInsets.zero, resizingMode: .stretch) 
UINavigationBar.appearance().setBackgroundImage(navBackgroundImage, for: .default) 
0

首先加入这一行你的appDelegate didFinishLaunchingWithOptionsMethod

UINavigationBar.appearance().barTintColor = UIColor.clear 

然后添加以下的viewDidLoad方法

if let image = UIImage(named: "header") { 
      UINavigationBar.appearance().setBackgroundImage(image.resizableImage(withCapInsets:UIEdgeInsets.zero, resizingMode: .stretch), for: .default) 
      UINavigationBar.appearance().contentMode = .scaleAspectFill 
} 
+0

它甚至不设置背景图像。只有白色导航栏 – iBug

+0

可以让我看看代码吗?,因为它适合我, – 3stud1ant3

+0

我刚刚复制并粘贴了你发布的相同代码。 – iBug

0

您应该使用调试点,以确保代码不会运行两次,然后:

let navBackgroundImage = UIImage(named: "header")!.resizableImage(withCapInsets: UIEdgeInsets.zero, resizingMode: .stretch) 
navigationController?.navigationBar.setBackgroundImage(navBackgroundImage, for: .default)