在NavigationBar上面添加UIView

时间:2018-04-28 11:26:04

标签: ios swift uinavigationbar

我需要在Swift中的状态栏和导航栏之间放置一个UIView。

我见过很多答案,但似乎都没有。

这是我的代码

    let newView = UIView()
    let label = UILabel()
    label.text = "header"
    newView.addSubview(label)
    UIApplication.shared.keyWindow?.addSubview(newView)

    let rootVC: HomeVC = UIStoryboard(.Home).instantiateViewController()
    navController = UINavigationController(rootViewController: rootVC)
    self.window?.rootViewController = self.navController
    self.window?.makeKeyAndVisible()

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:2)

你忘了设置视图和标签,就像

一样
let newView = UIView()
    newView.frame = CGRect(x:0,y:UIApplication.shared.statusBarFrame.height, width: view.frame.size.width, height: self.navigationController!.navigationBar.frame.height)
    newView.backgroundColor = UIColor.red
    let label = UILabel()
    label.frame = newView.bounds
    label.text = "header"
    newView.addSubview(label)
    UIApplication.shared.keyWindow?.addSubview(newView)

你得到OP作为

enter image description here

选项2

根据您的要求

    override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    // Do any additional setup after loading the view, typically from a nib.
    let newView = UIView()
    newView.frame = CGRect(x:0,y:UIApplication.shared.statusBarFrame.height, width: view.frame.size.width, height: 30)
    newView.backgroundColor = UIColor.red
    let label = UILabel()
    label.frame = newView.bounds
    label.text = "header"
    newView.addSubview(label)
    UIApplication.shared.keyWindow?.addSubview(newView)

    let bounds = self.navigationController!.navigationBar.bounds
    self.navigationController?.navigationBar.frame = CGRect(x: 0, y: newView.frame.size.height + newView.frame.origin.y, width: bounds.width, height: bounds.height  )
    }

enter image description here