为非透明导航栏swift 4设置背景图片

时间:2018-07-19 10:22:53

标签: ios swift

我想更改导航栏的背景色,同时将半透明性设置为false。它只是纯白色,在我为背景色设置图像之前不会改变。任何帮助将不胜感激。

let homeViewController = HomeViewController();
let navigationController = UINavigationController(rootViewController: homeViewController);
let navBar = navigationController.navigationBar;
navBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor:UIColor.white];
navBar.setBackgroundImage(UIImage(), for: .default);
navBar.shadowImage = UIImage();
navBar.isTranslucent = false;
navBar.backgroundColor = UIColor.red; //not working
navBar.tintColor = UIColor.red //not working

*编辑*

非常感谢你们,是的,请您进一步帮助我。我之所以要更改导航栏的颜色,是因为我想使其透明,以便可以为其添加渐变背景,现在可以使用barTintColor将其设置为clear。 但是还是这个

navBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor:UIColor.white];
navBar.setBackgroundImage(UIImage(), for: .default);
navBar.shadowImage = UIImage();
navBar.isTranslucent = false;
navBar.barTintColor = .clear;

不起作用,我仍然看不到我设置的渐变:

let bg = UIImageView(image: UIImage(named: "gradient"));
bg.frame = CGRect(x: 0, y:0, width: UIApplication.shared.statusBarFrame.width, height: UIApplication.shared.statusBarFrame.height + (navBar.frame.height));
bg.contentMode = .scaleAspectFill;
bg.layer.masksToBounds = true;
bg.layer.opacity = 1;
navigationController.view.insertSubview(bg, belowSubview: navBar);

我不只是使用setBackgroundImage设置背景图像的原因是我想更改背景图像在导航栏中的位置,因此它应该位于导航栏的右侧。

我知道我已经回答了我的问题,但这是真正的问题,仍然无法解决。无论你们是否回答我,我都会标记出最佳答案,但是如果您能进一步帮助我,我将不胜感激。

  • 编辑*

添加的图片

Image of The Problem

2 个答案:

答案 0 :(得分:3)

您设置了错误的属性。

设置barTintColor以应用背景色:

navBar.barTintColor = UIColor.red

以下是Apple文档:barTintColor

答案 1 :(得分:2)

此属性用于条形文本颜色。

navBar.tintColor

使用此功能:(用于NavBar背景色)。

navBar.barTintColor
相关问题