带有录制按钮的 Flash 动画问题 swift

Issue with flash animation with record button swift

我正在尝试制作一个录制按钮,以便当用户单击它时它开始录制,我想在该按钮上应用 flash 动画,我发现 THIS post。我将该代码转换为 swift 但它不起作用,这是我的 swift 代码:

var buttonFlashing = false
@IBAction func record(sender: AnyObject) {

    println("Button Tapped")
    if !buttonFlashing {
        startFlashingbutton()
    } else {
        stopFlashingbutton()
    }
}

func startFlashingbutton() {

    buttonFlashing = true
    recordButton.alpha = 1

    UIView.animateWithDuration(0.5 , delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut | UIViewAnimationOptions.Repeat | UIViewAnimationOptions.Autoreverse | UIViewAnimationOptions.AllowUserInteraction, animations: {

        self.recordButton.alpha = 0

        }, completion: {Bool in
    })
}

func stopFlashingbutton() {

    buttonFlashing = false

    UIView.animateWithDuration(0.1, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut | UIViewAnimationOptions.BeginFromCurrentState, animations: {

        self.recordButton.alpha = 1

        }, completion: {Bool in
    })
}

第一次按下按钮时正在打印 "Button Tapped" 并且出现动画,但是当我再次按下按钮时 "Button Tapped" 没有打印到控制台。而且我无法停止动画。

我找不到这里有什么问题。

您的代码存在的问题是 alpha 设置为零。因此,OS 在 alpha 为零或隐藏时禁用交互。动画应用于按钮层,它已经将 alpha 设置为最终值。因此,您可以将 alpha 值设置为低至 0.1 以启用用户交互,这应该没问题。

您可以执行以下任一选项,

将 alpha 设置为 0.1

UIView.animateWithDuration(0.5 , delay: 0.0, options: 
  [
    UIViewAnimationOptions.CurveEaseInOut, 
    UIViewAnimationOptions.Autoreverse,
    UIViewAnimationOptions.Repeat, 
    UIViewAnimationOptions.AllowUserInteraction
  ], 
  animations: {
    self.recordButton.alpha = 0.1        
  }, completion: {Bool in
})

或者,然后将图层的颜色设置为 clearColor,这在您的情况下似乎更明智。

UIView.animateWithDuration(0.5 , delay: 0.0, options: 
  [
    UIViewAnimationOptions.CurveEaseInOut, 
    UIViewAnimationOptions.Autoreverse,
    UIViewAnimationOptions.Repeat, 
    UIViewAnimationOptions.AllowUserInteraction
  ], 
  animations: {
    self.recordButton.layer.backgroundColor = UIColor.clearColor().CGColor       
  }, completion: {Bool in
})