简体   繁体   中英

Center image and add background in swift

So I have a screen that renders when the app is on the recents screen. But the issue is, it is on the top left and I can't align it to the center and also I couldn't set the background to white. The white background has to cover the screen and this image should be in middle. So far, I have managed to add the image. but no luck after that. Any help would be appreciated.

  override func applicationWillResignActive(_ application: UIApplication) {
   if let view = self.window.rootViewController?.view.subviews.first(where: {$0.tag == TAG_BLUR_VIEW}){
       view.removeFromSuperview()
       blurView = nil
   }
    if blurView == nil{
        blurView = UIImageView(image: UIImage(named: "splash.jpg"))
        blurView?.backgroundColor = UIColor .white
        blurView?.tag = TAG_BLUR_VIEW
    }
    
    self.window.rootViewController?.view.insertSubview(blurView!, at: 0)

  }

The simplest solution is to use a center position.

if blurView == nil {
   let centerPos = self.window?.rootViewController?.view.center ?? .zero
   blurView?.center = centerPos
   self.window?.rootViewController?.view.addSubview(blurView!)
}

So the final code snippet based on the provided code is like the following.
override func applicationWillResignActive(_ application: UIApplication) {
   if let view = self.window.rootViewController?.view.subviews.first(where: {$0.tag == TAG_BLUR_VIEW}){
       view.removeFromSuperview()
       blurView = nil
   }
    if blurView == nil{
        blurView = UIImageView(image: UIImage(named: "splash.jpg"))
        blurView?.backgroundColor = UIColor .white
        blurView?.tag = TAG_BLUR_VIEW

        let centerPos = self.window?.rootViewController?.view.center ?? .zero
        blurView?.center = centerPos
    }
    
    self.window.rootViewController?.view.insertSubview(blurView!, at: 0)

  }

You need to specify the constraints for your view.

override func viewDidLoad() {
        blurView.translatesAutoresizingMaskIntoConstraints = false
        blurView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
        // Add the other constraints such as topAnchor, leadingAnchor and trailingAnchor etc...
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM