Add UIView above NavigationBar

2019-08-23 10:18发布

问题:

I need to put a UIView between Status bar and Navigation bar in Swift.

I have seen many answers but none of the seems to work.

Here is my code

    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()

Any help will be appreciated

回答1:

you forgot to set the frame of view and label, do like

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)

you get OP as

Option 2

as per your required

    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  )
    }