缩放UIButton动画-Swift [关闭]


78

我正在尝试UIButton为其单击时进行缩放动画,但是我想要完成的是单击按钮时我需要将UIButton其缩小到内部,然后使其恢复到相同的大小(如气泡)。

我尝试了以下方法:

button.transform = CGAffineTransformMakeScale(-1, 1)

UIView.animateWithDuration(0.5, animations: { () -> Void in

    button.transform = CGAffineTransformMakeScale(1,1)

})

当您尝试包含的代码时会发生什么?
罗伯特·哥伦比亚

Answers:


177

试试这个

UIView.animate(withDuration: 0.6,
    animations: {
        self.button.transform = CGAffineTransform(scaleX: 0.6, y: 0.6)
    },
    completion: { _ in
        UIView.animate(withDuration: 0.6) {
            self.button.transform = CGAffineTransform.identity
        }
    })

9
Swift 3.0:UIView.animate(withDuration:0.6,动画:{self.button.transform = CGAffineTransform(scaleX:0.6,y:0.6)},完成:{(完成:Bool)在UIView.animate(withDuration:0.6,动画中:{self.button.transform = CGAffineTransform.identity})})
agfa555

@nRewik使用了相同的代码,但是按钮未设置动画。请帮助
Thripthi Haridas '18

68

SWIFT 5代码更新:我的动画按钮具有很好的弹跳效果,并带有弹簧动画。

@IBOutlet weak var button: UIButton!

@IBAction func animateButton(sender: UIButton) {

    sender.transform = CGAffineTransform(scaleX: 0.6, y: 0.6)

    UIView.animate(withDuration: 2.0,
                               delay: 0,
                               usingSpringWithDamping: CGFloat(0.20),
                               initialSpringVelocity: CGFloat(6.0),
                               options: UIView.AnimationOptions.allowUserInteraction,
                               animations: {
                                sender.transform = CGAffineTransform.identity
        },
                               completion: { Void in()  }
    )
}

漂亮的动画。谢谢!
BharathRao

太好了 很棒的动画!!!
AJ Hernandez

29

以上所有答案均有效。
另外,我建议使用Swift创建一个UIView扩展,以“缩放”所需的任何视图。
您可以从这段代码中获得启发:

SWIFT 5.0

extension UIView {

/**
 Simply zooming in of a view: set view scale to 0 and zoom to Identity on 'duration' time interval.

 - parameter duration: animation duration
 */
func zoomIn(duration: TimeInterval = 0.2) {
    self.transform = CGAffineTransform(scaleX: 0.0, y: 0.0)
    UIView.animate(withDuration: duration, delay: 0.0, options: [.curveLinear], animations: { () -> Void in
        self.transform = .identity
        }) { (animationCompleted: Bool) -> Void in
    }
}

/**
 Simply zooming out of a view: set view scale to Identity and zoom out to 0 on 'duration' time interval.

 - parameter duration: animation duration
 */
func zoomOut(duration : TimeInterval = 0.2) {
    self.transform = .identity
    UIView.animate(withDuration: duration, delay: 0.0, options: [.curveLinear], animations: { () -> Void in
        self.transform = CGAffineTransform(scaleX: 0.0, y: 0.0)
        }) { (animationCompleted: Bool) -> Void in
    }
}

/**
 Zoom in any view with specified offset magnification.

 - parameter duration:     animation duration.
 - parameter easingOffset: easing offset.
 */
func zoomInWithEasing(duration: TimeInterval = 0.2, easingOffset: CGFloat = 0.2) {
    let easeScale = 1.0 + easingOffset
    let easingDuration = TimeInterval(easingOffset) * duration / TimeInterval(easeScale)
    let scalingDuration = duration - easingDuration
    UIView.animate(withDuration: scalingDuration, delay: 0.0, options: .curveEaseIn, animations: { () -> Void in
        self.transform = CGAffineTransform(scaleX: easeScale, y: easeScale)
        }, completion: { (completed: Bool) -> Void in
            UIView.animate(withDuration: easingDuration, delay: 0.0, options: .curveEaseOut, animations: { () -> Void in
                self.transform = .identity
                }, completion: { (completed: Bool) -> Void in
            })
    })
}

/**
 Zoom out any view with specified offset magnification.

 - parameter duration:     animation duration.
 - parameter easingOffset: easing offset.
 */
func zoomOutWithEasing(duration: TimeInterval = 0.2, easingOffset: CGFloat = 0.2) {
    let easeScale = 1.0 + easingOffset
    let easingDuration = TimeInterval(easingOffset) * duration / TimeInterval(easeScale)
    let scalingDuration = duration - easingDuration
    UIView.animate(withDuration: easingDuration, delay: 0.0, options: .curveEaseOut, animations: { () -> Void in
        self.transform = CGAffineTransform(scaleX: easeScale, y: easeScale)
        }, completion: { (completed: Bool) -> Void in
            UIView.animate(withDuration: scalingDuration, delay: 0.0, options: .curveEaseOut, animations: { () -> Void in
                self.transform = CGAffineTransform(scaleX: 0.0, y: 0.0)
                }, completion: { (completed: Bool) -> Void in
            })
    })
}

}

用法非常简单:

let button = UIButton(frame: frame)
button.zoomIn() // here the magic

Swift 3版本

extension UIView {

/**
 Simply zooming in of a view: set view scale to 0 and zoom to Identity on 'duration' time interval.

 - parameter duration: animation duration
 */
func zoomIn(duration: TimeInterval = 0.2) {
    self.transform = CGAffineTransform(scaleX: 0.0, y: 0.0)
    UIView.animate(withDuration: duration, delay: 0.0, options: [.curveLinear], animations: { () -> Void in
        self.transform = CGAffineTransform.identity
    }) { (animationCompleted: Bool) -> Void in
    }
}

/**
 Simply zooming out of a view: set view scale to Identity and zoom out to 0 on 'duration' time interval.

 - parameter duration: animation duration
 */
func zoomOut(duration: TimeInterval = 0.2) {
    self.transform = CGAffineTransform.identity
    UIView.animate(withDuration: duration, delay: 0.0, options: [.curveLinear], animations: { () -> Void in
        self.transform = CGAffineTransform(scaleX: 0.0, y: 0.0)
    }) { (animationCompleted: Bool) -> Void in
    }
}

/**
 Zoom in any view with specified offset magnification.

 - parameter duration:     animation duration.
 - parameter easingOffset: easing offset.
 */
func zoomInWithEasing(duration: TimeInterval = 0.2, easingOffset: CGFloat = 0.2) {
    let easeScale = 1.0 + easingOffset
    let easingDuration = TimeInterval(easingOffset) * duration / TimeInterval(easeScale)
    let scalingDuration = duration - easingDuration
    UIView.animate(withDuration: scalingDuration, delay: 0.0, options: .curveEaseIn, animations: { () -> Void in
        self.transform = CGAffineTransform(scaleX: easeScale, y: easeScale)
    }, completion: { (completed: Bool) -> Void in
        UIView.animate(withDuration: easingDuration, delay: 0.0, options: .curveEaseOut, animations: { () -> Void in
            self.transform = CGAffineTransform.identity
        }, completion: { (completed: Bool) -> Void in
        })
    })
}

/**
 Zoom out any view with specified offset magnification.

 - parameter duration:     animation duration.
 - parameter easingOffset: easing offset.
 */
func zoomOutWithEasing(duration: TimeInterval = 0.2, easingOffset: CGFloat = 0.2) {
    let easeScale = 1.0 + easingOffset
    let easingDuration = TimeInterval(easingOffset) * duration / TimeInterval(easeScale)
    let scalingDuration = duration - easingDuration
    UIView.animate(withDuration: easingDuration, delay: 0.0, options: .curveEaseOut, animations: { () -> Void in
        self.transform = CGAffineTransform(scaleX: easeScale, y: easeScale)
    }, completion: { (completed: Bool) -> Void in
        UIView.animate(withDuration: scalingDuration, delay: 0.0, options: .curveEaseOut, animations: { () -> Void in
            self.transform = CGAffineTransform(scaleX: 0.0, y: 0.0)
        }, completion: { (completed: Bool) -> Void in
        })
    })
}

}

20

迅捷3.x +

extension UIButton {

        func pulsate() {

            let pulse = CASpringAnimation(keyPath: "transform.scale")
            pulse.duration = 0.2
            pulse.fromValue = 0.95
            pulse.toValue = 1.0
            pulse.autoreverses = true
            pulse.repeatCount = 2
            pulse.initialVelocity = 0.5
            pulse.damping = 1.0

            layer.add(pulse, forKey: "pulse")
        }

        func flash() {

            let flash = CABasicAnimation(keyPath: "opacity")
            flash.duration = 0.2
            flash.fromValue = 1
            flash.toValue = 0.1
            flash.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
            flash.autoreverses = true
            flash.repeatCount = 3

            layer.add(flash, forKey: nil)
        }


        func shake() {

            let shake = CABasicAnimation(keyPath: "position")
            shake.duration = 0.05
            shake.repeatCount = 2
            shake.autoreverses = true

            let fromPoint = CGPoint(x: center.x - 5, y: center.y)
            let fromValue = NSValue(cgPoint: fromPoint)

            let toPoint = CGPoint(x: center.x + 5, y: center.y)
            let toValue = NSValue(cgPoint: toPoint)

            shake.fromValue = fromValue
            shake.toValue = toValue

            layer.add(shake, forKey: "position")
        }
    }

用法:

myButton.flash()
// myButton.pulsate()
// myButton.shake()

鸣谢:肖恩·艾伦


15

Swift 3版本:

    UIView.animate(withDuration: 0.6, animations: {
        button.transform = CGAffineTransform.identity.scaledBy(x: 0.6, y: 0.6)
        }, completion: { (finish) in
            UIView.animate(withDuration: 0.6, animations: {
                button.transform = CGAffineTransform.identity
            })
    })

8

使用Swift 4 Xcode 9,这将在初次按下时使按钮动画,然后在释放时返回动画。

extension UIView {

func animateButtonDown() {

    UIView.animate(withDuration: 0.1, delay: 0.0, options: [.allowUserInteraction, .curveEaseIn], animations: {
        self.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
    }, completion: nil)
}

func animateButtonUp() {

    UIView.animate(withDuration: 0.1, delay: 0.0, options: [.allowUserInteraction, .curveEaseOut], animations: {
        self.transform = CGAffineTransform.identity
    }, completion: nil)
}

实现方式:

@IBAction func buttonTouchDown(_ sender: UIButton) {
    //Connected with Touch Down Action
    sender.animateButtonDown()
}

@IBAction func buttonTouchUpOutside(_ sender: UIButton) {
    //Connected with Touch Up Outside Action
    //if touch moved away from button
    sender.animateButtonUp()
}

@IBAction func buttonTouchUpInside(_ sender: UIButton) {
    //Connected with Touch Up Inside Action
    sender.animateButtonUp()
    //code to execute when button pressed
}

7

它与我的工作方式如下,将动画设置为较小,然后在开始动画时恢复到其原始大小:

迅捷2

button.transform = CGAffineTransformMakeScale(0.6, 0.6)

UIView.animateWithDuration(0.3, animations: { () -> Void in

    button.transform = CGAffineTransformMakeScale(1,1)

})

斯威夫特3,4,5

button.transform = CGAffineTransform.init(scaleX: 0.6, y: 0.6)

UIView.animate(withDuration: 0.3, animations: { () -> Void in

    button.transform = CGAffineTransform.init(scaleX: 1, y: 1)

})

您的代码立即将按钮的大小设置为0.6,然后将其重新设置为原始大小。但是,如果要设置动画为0.6,然后再设置动画为原始大小。看看我的答案。
nRewik

@nRewik,我将检查出来:)
AaoIi 2015年

5

我更喜欢使用新闻动画,并比其他示例更快地设置动画,并使用完成控件等待动画结束:

迅捷3

extension UIButton {
   func press(completion:@escaping ((Bool) -> Void)) {
            UIView.animate(withDuration: 0.05, animations: {
                self.transform = CGAffineTransform(scaleX: 0.8, y: 0.8) }, completion: { (finish: Bool) in
                    UIView.animate(withDuration: 0.1, animations: {
                        self.transform = CGAffineTransform.identity
                        completion(finish)
                    })
            })
    }
}

用法

@IBAction func playPauseBtnTap(_ sender: Any) {
     let playPauseBtn = sender as! UIButton
     playPauseBtn.press(completion:{ finish in
         if finish {
             print("animation ended")
         }
     }
}

1
在一个线程很好地利用完成推出的东西,而不具有荒谬旋转的圆圈废话
μολὼν.λαβέ

3

使用以下动画,按钮将从其全尺寸开始,并通过弹簧动画减小到0.6,以弹回其全尺寸。

[UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.4 initialSpringVelocity:0.3 options:0 animations:^{
                //Animations
                button.transform = CGAffineTransformIdentity;
                CGAffineTransformMakeScale(0.6, 0.6)
            } completion:^(BOOL finished) {
                //Completion Block
            [UIView.animateWithDuration(0.5){
            button.transform = CGAffineTransformIdentity
             }];
            }];

3

如果您想要带有完成处理程序的自动反转效果,可以尝试一下。

viewToAnimate.transform = CGAffineTransform(scaleX: 0.1, y: 0.1)
        UIView.animate(withDuration: 0.7, // your duration
                       delay: 0,
                       usingSpringWithDamping: 0.2,
                       initialSpringVelocity: 6.0,
                       animations: { _ in
                       viewToAnimate.transform = .identity
            },
                       completion: { _ in
                        // Implement your awesome logic here.
        })

2

iOS 9和xCode 7

//for zoom in
    [UIView animateWithDuration:0.5f animations:^{

        self.sendButton.transform = CGAffineTransformMakeScale(1.5, 1.5);
    } completion:^(BOOL finished){}];
// for zoom out
        [UIView animateWithDuration:0.5f animations:^{

            self.sendButton.transform = CGAffineTransformMakeScale(1, 1);
        }completion:^(BOOL finished){}];

2

这将产生奇妙的弹跳效果:

@IBAction func TouchUpInsideEvent(sender: UIButton) {
    UIView.animateWithDuration(2.0,
                               delay: 0,
                               usingSpringWithDamping: CGFloat(0.20),
                               initialSpringVelocity: CGFloat(6.0),
                               options: UIViewAnimationOptions.AllowUserInteraction,
                               animations: {
                                sender.transform = CGAffineTransformIdentity
        },
                               completion: { Void in()  }
    )
}


@IBAction func touchDownEvent(sender: UIButton) {
    UIView.animateWithDuration(0.15, animations: {
        sender.transform = CGAffineTransformMakeScale(0.6, 0.6)
    })

}

2

缩放按钮或大约三倍或更多倍的任何视图都使用以下代码。使用xcode 9的swift 3或swift 4。

 UIView.animate(withDuration: 0.2, animations: {
        self.cartShowHideBtnView.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)

    }, completion: { (finish: Bool) in
            UIView.animate(withDuration: 0.2, animations: {
                self.cartShowHideBtnView.transform = CGAffineTransform.identity

            }, completion:{(finish: Bool) in
                UIView.animate(withDuration: 0.2, animations: {
                    self.cartShowHideBtnView.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)

                }, completion: { (finish: Bool) in
                    UIView.animate(withDuration: 0.2, animations: {
                        self.cartShowHideBtnView.transform = CGAffineTransform.identity

                    }, completion:{(finish: Bool) in
                        UIView.animate(withDuration: 0.2, animations: {
                            self.cartShowHideBtnView.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)

                        }, completion: { (finish: Bool) in
                            UIView.animate(withDuration: 0.2, animations: {
                                self.cartShowHideBtnView.transform = CGAffineTransform.identity
                        })
                    })
                })
            })
        })
    })

1

我使用Swift 4编写了一个协议,可以在要动画的某些特定UIViews上使用...您可以在此处尝试一些动画或更改时间和延迟。

推荐这种方法,因为您可以在一个视图中使用此协议和其他协议,并且该视图可以使用此功能,并且从UIView进行大量的OS扩展都会产生代码味道。

import Foundation
import UIKit

protocol Showable where Self: UIView {}

extension Showable {

    func show(_ view: UIView? = nil) {

        if let view = view {
            self.animate(view)
        } else {
            self.animate(self)
        }
    }

    private func animate(_ view: UIView) {
        view.transform = CGAffineTransform(scaleX: 0.0, y: 0.0)

        UIView.animate(withDuration: 2.0,
                       delay: 0,
                       usingSpringWithDamping: CGFloat(0.20),
                       initialSpringVelocity: CGFloat(6.0),
                       options: [.allowUserInteraction],
                       animations: {
                        view.transform = CGAffineTransform.identity
        })
    }
}

还请添加使用此扩展程序的示例。
Hemang,

0

这是一个工作示例:

extension  UIButton{
  func flash() {
    let flash = CABasicAnimation(keyPath: "opacity")
    flash.duration = 0.5
    flash.fromValue = 1
    flash.toValue = 0.1
    flash.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
    flash.autoreverses = true
    flash.repeatCount = 3
    layer.add(flash, forKey: nil)
  }
}

@IBAction func taptosave(_ sender: UIButton) {
  sender.flash()
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.