14

I have found one similar question to this but it did not answer my question. I have a UIButton which is animating from the bottom of the screen to the top. I would like to be able to use the button while it is moving. Now, the button can only be used when the animation has finished and the button is no longer animating. Also, I've heard that I might need to use something called NSTimer?

class ViewController: UIViewController {

    @IBAction func button2(sender: UIButton) {
        button.hidden = false
        button.center = CGPointMake(126, 380);        
        UIView.animateKeyframesWithDuration(3, delay: 0, options:   .AllowUserInteraction,
            animations: { () -> Void in
            self.button.center = CGPointMake(126, 130 )
            }) { (_) -> Void in
        }   
    }   

    @IBOutlet var label: UILabel! 
    @IBOutlet var button: UIButton!

    @IBAction func button1(sender: UIButton) {
        button.hidden = true
        label.hidden = false
    }   

    override func viewDidLoad() {
        super.viewDidLoad() 
        button.hidden = true
        label.hidden = true
    } 
}
Daniel Storm
  • 18,301
  • 9
  • 84
  • 152
Anton O.
  • 653
  • 7
  • 27

1 Answers1

8

You have to use a CADisplayLink. For example:

@IBOutlet var button2: UIButton!

@IBAction func button3(sender: UIButton)
{
    label.hidden = false
    button2.hidden = true
}

@IBAction func button1(sender: UIButton)
{
    button2.frame = CGRectMake(120, 400, 100, 100)
    let displayLink = CADisplayLink(target: self, selector: "handleDisplayLink:")
    displayLink.addToRunLoop(NSRunLoop.currentRunLoop(), forMode:   NSDefaultRunLoopMode)
}

func handleDisplayLink(displayLink: CADisplayLink)
{
    var buttonFrame = button2.frame
    buttonFrame.origin.y += -2
    button2.frame = buttonFrame

    if button2.frame.origin.y <= 50 
    {
        displayLink.invalidate()
    }
}

You can also check this question: Moving a button in swift using animate with duration with constraints and detecting a touch during it

Community
  • 1
  • 1
Anton O.
  • 653
  • 7
  • 27