1

I'm trying to put a UIview() to cover the full screen so when i press a button i can put a dark mode theme on it. it works ok the only problem is that it does not cover the nav bar which is something i want to do i have looked up a few things i found this code it works on the tutorial i have seen but does not work now think swift have updated the language making that solution old

    if let window = UIApplication.shared.keyWindow {
        let blackView = UIView()
        blackView.backgroundColor = .black
        view.addSubview(blackView)
               blackView.frame = window.frame



    } 
General Grievance
  • 4,555
  • 31
  • 31
  • 45

1 Answers1

2

Swift 4.X

You can add extension in your project.

extension UIView {

    func addToWindow()  {
        let window = UIApplication.shared.keyWindow!
        self.frame = window.bounds
        window.addSubview(self)
    }
}

Use:

bgView = UIView(frame: UIScreen.main.bounds)
bgView.backgroundColor = UIColor(white: 0, alpha: 0.4)
bgView.addToWindow()
dahiya_boy
  • 9,298
  • 1
  • 30
  • 51
  • Xcode says "'keyWindow' was deprecated in iOS 13.0. Should not be used for applications that support multiple scenes as it returns a key window across all connected scenes" – Zhou Haibo May 31 '21 at 15:59
  • @ChuckZHB Solution already available https://stackoverflow.com/questions/57134259/how-to-resolve-keywindow-was-deprecated-in-ios-13-0 – dahiya_boy May 31 '21 at 17:08
  • Thanks for it. After trying some code way, didn't work for me. Then In IB, I change holder view's top and bottom anchor to constraint on its superview(view) instead of safe area, that lets holder view fill the whole screen. – Zhou Haibo May 31 '21 at 17:23