如何在动画时使用UIButton

时间:2015-12-05 02:09:35

标签: ios swift animation uibutton

我发现了一个类似的问题,但它没有回答我的问题。 我有一个UIButton,它从屏幕底部到顶部动画。我希望能够在移动时使用按钮。现在,该按钮只能在动画结束且按钮不再动画时使用。另外,我听说我可能需要使用名为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
    } 
}

1 个答案:

答案 0 :(得分:8)

您必须使用CADisplayLink。例如:

@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()
    }
}

您还可以查看此问题:Moving a button in swift using animate with duration with constraints and detecting a touch during it