2016-08-15 330 views
0

我有一個按鈕,我已經用一個圖標取代,當圖標是clicke時,我希望它放大和縮小可以說5秒。我怎樣才能做到這一點?我爲按鈕製作了一組5幅不同尺寸的圖像,我可以通過它們循環或者有其他方法嗎?動畫UIButton放大和縮小點擊

@IBAction func myButton(sender: UIButton){ 
    //animation that zoom the button icon in and out 
} 

編輯:林使用的Xcode 6.4

+0

看一看http://stackoverflow.com/questions/14184619/how-can-i-animate-zoom-in-zoom-out-on-ios-using-objective-c – Yannick

回答

2

這將放大和縮小按鈕,而無需使用額外的圖像:

let timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: "stopButtonAnimation", userInfo: nil, repeats: false) 
let options = UIViewAnimationOptions.Autoreverse | UIViewAnimationOptions.Repeat | UIViewAnimationOptions.CurveEaseInOut 
UIView.animateWithDuration(0.25, delay: 0, options: options, 
animations: { 
    self.button.transform = CGAffineTransformMakeScale(0.5, 0.5) 
}, completion:nil) 

.....

func stopButtonAnimation() { 
    button.layer.removeAllAnimations; 
} 
+0

我是否把這個放在我的IBAction函數中? –

+0

@TheDude是的,你應該 –

+0

這太棒了!是否有可能使這個循環開啓一段時間? –

6

要展示另一種方法,我將展示一種使用圖層動畫的方法。 更多的相關信息吧here

將此代碼添加到您的功能(提示是代碼中的註釋):

// specify the property you want to animate 
let zoomInAndOut = CABasicAnimation(keyPath: "transform.scale") 
// starting from the initial value 1.0 
zoomInAndOut.fromValue = 1.0 
// to scale down you set toValue to 0.5 
zoomInAndOut.toValue = 0.5 
// the duration for the animation is set to 1 second 
zoomInAndOut.duration = 1.0 
// how many times you want to repeat the animation 
zoomInAndOut.repeatCount = 5 
// to make the one animation(zooming in from 1.0 to 0.5) reverse to two animations(zooming back from 0.5 to 1.0) 
zoomInAndOut.autoreverses = true 
// because the animation consists of 2 steps, caused by autoreverses, you set the speed to 2.0, so that the total duration until the animation stops is 5 seconds 
zoomInAndOut.speed = 2.0 
// add the animation to your button 
button.layer.addAnimation(zoomInAndOut, forKey: nil) 

結果:

enter image description here

+1

更好的方法! –