我正在尝试实现UIButton
的平滑触摸效果,就像我们在iPhone
设备上使用计算器一样。然而,我已经尝试了一些Objective-C
和Swift
代码,但发现结果并不如期望。
尝试过的代码:
@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 c
和TouchUpInside
和TouchDown
事件,但结果相同。
感谢您的时间。