Search code examples
iosswiftuiviewanimationcgpoint

How to transform multiple view to same location(CGPoint)


I've got multiple UIImageViews, spread across in a view.

@IBOutlet var leftIVs: [UIImageView]!
@IBOutlet var topIVs: [UIImageView]!
@IBOutlet var rightIVs: [UIImageView]!

I'm trying to create a function using UIView.animate... functions and 'transform' property which brings all of these UIImageViews at the center of the superview. I'm using the following code:

let performInitialTransformation: ((UIImageView)->()) = { (card) in
    let cardCenter = CGPoint(x: card.frame.midX, y: card.frame.midY)
    let viewCenter = CGPoint(x: self.view.bounds.midX, y: self.view.bounds.midY)
    let deltaPoint = cardCenter - viewCenter //also tried (viewCenter - cardCenter)
    UIView.animate(withDuration: 0.5, animations: {
        card.transform = CGAffineTransform.init(translationX: deltaPoint.x, y: deltaPoint.y)
    }) { (done) in 
    }
}

for card in topIVs {
    performInitialTransformation(card)
}

for card in leftIVs {
    performInitialTransformation(card)
}

for card in rightIVs {
    performInitialTransformation(card)
}

I'm using this static function:

extension CGPoint {
    static func -(lhs: CGPoint, rhs: CGPoint) -> CGPoint {
        return CGPoint(x: rhs.x - lhs.x, y: rhs.y - lhs.y)
    }
}

NOTE: Also, I will be bringing those images back to there original position afterward for which I will use CGAffineTransform.identity

The images are not being shown in the center. How can I achieve this? Thanks in advance!


Solution

  • I think your problem was that you didn't reduce the size of the image view so that they stack at the exact centre of the screen.

    let deltaX = (self.view.center.x - card.frame.minX) - card.frame.width/2
    let deltaY = (self.view.center.y - card.frame.minY) - card.frame.height/2
    UIView.animate(withDuration: 1) {
        card.transform = .init(translationX: deltaX, y: deltaY)
    }
    

    enter image description here