6

I have a simple Swift macOS app (using Xcode 8.2.1) that contains a single NSButton. When I click the button I would like it to fade out over a specified period. I thought I could use NSAnimationContext but no matter what value I set the context duration the button fades out almost immediately. Is this not the right way to do this?

class ViewController: NSViewController {

  @IBOutlet weak var basicButton: NSButton!

  override func viewDidLoad() {
    super.viewDidLoad()
  }

  @IBAction func basicButtonClicked(_ sender: NSButton) {
    NSAnimationContext.runAnimationGroup({ (context) in
      context.duration = 10.0
      self.basicButton.animator().alphaValue = 1
    }) { 
      self.basicButton.animator().alphaValue = 0
    }
  }
}
RobertJoseph
  • 7,968
  • 12
  • 68
  • 113

1 Answers1

6

I misunderstood how the animator values worked during the animation. The right way to set this up is:

@IBAction func basicButtonClicked(_ sender: NSButton) {
  NSAnimationContext.runAnimationGroup({ (context) in
    context.duration = 10.0
    // Use the value you want to animate to (NOT the starting value)
    self.basicButton.animator().alphaValue = 0
  })
}
RobertJoseph
  • 7,968
  • 12
  • 68
  • 113
  • 3
    An important thing to note here that you need to reach for the button's `.animator()` method to get its animator proxy object! Don't change the `alphaValue` directly. (Took me a bit to notice this!) – huwr Jun 17 '18 at 08:18