Search code examples
iosswiftcgrectuiwindowcgpoint

Swift -Position new UIWIndow in center of Screen


The user taps a cell, I get the touchLocation, create and then animate a new UIWindow to the center of the screen. The problem is when the new window (purple) appears on screen instead of its center being in the center of the screen, its x,y coordinate starts at the center of the screen.

I get this:

enter image description here

But I want this:

enter image description here

// the collectionView is dimmed black, that's why the background color is dark
guard let keyWindow = UIApplication.shared.keyWindow else { return }

let startingRect = CGRect(x: userTouchPointX, y: userTouchPointY, width: 10, height: 10)

let newWindow = UIWindow(frame: startingRect)
newWindow.backgroundColor = .clear
newWindow.windowLevel = UIWindow.Level.normal
newWindow.rootViewController = UINavigationController(rootViewController: PurpleVC())
newWindow.isHidden = false
newWindow.makeKey()

let endingCenterX = keyWindow.screen.bounds.midX // I also tried keyWindow.frame.width / 2 and also UIScreen.main.bounds.width / 2
let endingCenterY = keyWindow.screen.bounds.midY // I also tried keyWindow.frame.height / 2 and also UIScreen.main.bounds.height / 2
let endingWidth = keyWindow.frame.width
let endingHeight: CGFloat = 200

let endingCenter = CGPoint(x: endingCenterX, y: endingCenterY)

UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: [.curveEaseIn], animations: {

    newWindow.center = endingCenter
    newWindow.frame.size.width = endingWidth
    newWindow.frame.size.height = endingHeight
}) { (_) in

    newWindow.layoutIfNeeded()
}

Solution

  • Change your center After setting the frame of the window will solve your issue ... hopefully it will help

    // newWindow.center = endingCenter remove from here
        newWindow.frame.size.width = endingWidth
        newWindow.frame.size.height = endingHeight
        newWindow.center = endingCenter // add it here