Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fade out NSButton using NSAnimationContext

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
    }
  }
}
like image 785
RobertJoseph Avatar asked Feb 09 '17 12:02

RobertJoseph


1 Answers

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
  })
}
like image 186
RobertJoseph Avatar answered Oct 23 '22 20:10

RobertJoseph