Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
596 views
in Technique[技术] by (71.8m points)

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

  }
image question from:https://stackoverflow.com/questions/66049407/center-image-and-add-background-in-swift

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...