Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Animation to scale and move UIView (swift)

I have a UIView, placed in the middle of the screen. When the user presses a button, I want it to move up near top of the screen as it shrinks to about a fifth of its size.

I have tried this:

UIView.animateWithDuration(0.7) { () -> Void in
            self.main.transform = CGAffineTransformMakeScale(0.2, 0.2)
            self.main.transform = CGAffineTransformMakeTranslation(0, -250)
        }

But for some reason, that only scales the view. I have also tried to put this in the animateWithDuration:

self.main.frame = CGRectMake(self.view.frame.width/2 - 10, 50, 50, 50)

How can I get both animations to work?

question from:https://stackoverflow.com/questions/40318081/animation-to-scale-and-move-uiview-swift

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

1 Reply

0 votes
by (71.8m points)

Joe's answer above does exactly as his GIF describes but it doesn't really answer your question since it translates then scales the view (as opposed to both translating and scaling at the same time). Your issue is that you're setting the view's transform in your animation block then immediately overwritting that value with another transform. To achieve both translation and scale at the same time, you'll want something like this:

@IBAction func animateButton(_ sender: UIButton) {
    let originalTransform = self.main.transform
    let scaledTransform = originalTransform.scaledBy(x: 0.2, y: 0.2)
    let scaledAndTranslatedTransform = scaledTransform.translatedBy(x: 0.0, y: -250.0)
    UIView.animate(withDuration: 0.7, animations: {
        self.main.transform = scaledAndTranslatedTransform
    })
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...