我正在尝试为UINavigationBar设置背景图片。我已经在Objective-C中做了很多次,但是很快,我遇到了一个问题。我搜索并尝试了很多东西,但没有一个对我有用。
以下是我正在使用的代码:
let navBackgroundImage:UIImage! = UIImage(named: "header")
self.navigationController?.navigationBar.setBackgroundImage(navBackgroundImage, for: .default)
我的标题图片有以下尺寸:
375×64表示1x,依此类推2x和3x。我也尝试过使用320x64,但它仍然不起作用。
屏幕截图:
有什么建议吗?
修改
尝试后
self.navigationController?.navigationBar.setBackgroundImage(UIImage(named: "header")?.resizableImage(withCapInsets: UIEdgeInsetsMake(0, 0, 0, 0), resizingMode: .stretch), for: .default)
答案 0 :(得分:2)
试试这个,
<强>夫特强>
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];
答案 1 :(得分:0)
尝试打印或使用调试点以确保您的代码未被调用两次,或使用
let navBackgroundImage:UIImage! = UIImage(named: "header")!.resizableImage(withCapInsets: UIEdgeInsets.zero, resizingMode: .stretch)
UINavigationBar.appearance().setBackgroundImage(navBackgroundImage, for: .default)
答案 2 :(得分: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
}
答案 3 :(得分:0)
您应该使用调试点来确保代码不会运行两次,然后:
let navBackgroundImage = UIImage(named: "header")!.resizableImage(withCapInsets: UIEdgeInsets.zero, resizingMode: .stretch)
navigationController?.navigationBar.setBackgroundImage(navBackgroundImage, for: .default)