UIButton 平滑触摸效果

vai*_*hav 4 objective-c uibutton ios swift

我正在尝试实现UIButton's平滑的触摸效果,就像我们在iPhone设备中使用计算器一样。但是我已经尝试了一些代码Objective c,并Swift为良好,但发现了同样的结果是达不到的欲望。

试过的代码:

@IBAction func someAction(sender: UIButton){
    button.setBackgroundColor(UIColor.blackColor(), forState: UIControlState.Highlighted)
}
Run Code Online (Sandbox Code Playgroud)
// using extension
extension UIButton {
    func setBackgroundColor(color: UIColor, forState: UIControlState) {
        UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
        CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), color.CGColor)
        CGContextFillRect(UIGraphicsGetCurrentContext(), CGRect(x: 0, y: 0, width: 1, height: 1))
        let colorImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        self.setBackgroundImage(colorImage, forState: forState)
    }}
Run Code Online (Sandbox Code Playgroud)

说明:上面的代码可以正常工作,但应用的效果不是那么流畅。事实上,当我触摸按钮时,需要一纳秒的时间在其上应用背景图像,当我释放触摸时,背景图像突然消失。

我也在Objective cusingTouchUpInsideTouchDownevent 中尝试过这个,但结果发现相同。

谢谢你的时间。

vai*_*hav 5

完整的解决方案:使用CABasicAnimation并在按钮上添加一个图层。

@IBAction func someAction(sender: UIButton){
   let colorAnimation = CABasicAnimation(keyPath: "backgroundColor")
   colorAnimation.fromValue = UIColor.redColor().CGColor
   colorAnimation.duration = 1  // animation duration
   // colorAnimation.autoreverses = true // optional in my case 
   // colorAnimation.repeatCount = FLT_MAX // optional in my case 
   sender.layer.addAnimation(colorAnimation, forKey: "ColorPulse")
}
Run Code Online (Sandbox Code Playgroud)

参考:作为用户 iOS_devloper评论