UIButton光滑触摸效果

4

我正在尝试实现UIButton的平滑触摸效果,就像我们在iPhone设备上使用计算器一样。然而,我已经尝试了一些Objective-CSwift代码,但发现结果并不如期望。

尝试过的代码:

@IBAction func someAction(sender: UIButton){
    button.setBackgroundColor(UIColor.blackColor(), forState: UIControlState.Highlighted)
}

// 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)
    }}

说明:上述代码按照我的要求可以正常工作,但应用的效果不够平滑。实际上,当我点击按钮时,需要花费一纳秒的时间才能将背景图像应用到它上面,而当我释放触摸时,背景图像突然消失。

我还尝试了使用Objective cTouchUpInsideTouchDown事件,但结果相同。

感谢您的时间。


慢的部分是按钮扩展中的CoreGraphics处理。为什么不能只使用UIButton setBackgroundColor来更改颜色呢? - GeneCode
@GeneCode,这不是关于改变颜色的问题,而是关于在按钮上应用效果的问题。 - vaibhav
3个回答

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")
}

参考:iOS 开发者 的评论


1

创建UIButton的子类并重写highlighted属性:

override var highlighted: Bool {
        get {
            return super.highlighted
        }
        set {
            if newValue {
                backgroundColor = UIColor.blackColor()
            }
            else {
                backgroundColor = UIColor.whiteColor()
            }
            super.highlighted = newValue
        }
    }

1
如果你想在从高亮到正常状态改变背景颜色时添加某种动画效果...你可以在改变背景颜色时添加动画效果--让colorAnimation = CABasicAnimation(keyPath: "backgroundColor") colorAnimation.fromValue = UIColor.redColor().CGColor colorAnimation.toValue = UIColor.blueColor().CGColor colorAnimation.duration = 1 colorAnimation.autoreverses = true colorAnimation.repeatCount = FLT_MAX self.layer.addAnimation(colorAnimation, forKey: "ColorPulse") - PlusInfosys

-2

为您的按钮分配属性,并将此代码放入viewDidLoad中。

yourButton.setBackgroundColor(UIColor.blackColor(), forState: UIControlState.Highlighted)

问题在于您仅在用户按下按钮时设置它。由于使用了CoreGraphics,此代码需要时间。您可以在viewdidload中立即为高亮状态设置背景图像,它将保留在那里,并在您点击按钮时立即调用。

等一下,让我应用一下。 - vaibhav
你的代码运行良好,就像我所做的那样,但问题仍然存在。 - vaibhav
设置背景颜色没有 "forState:" 属性。请更改您的答案。 - veeresh kumbar
我无法更改答案,因为该属性存在于2016年,代码引用了iOS的那个特定版本。 - GeneCode

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接