簡體   English   中英

如何在CADisplayLink中設置延遲

[英]How to set up a delay in a CADisplayLink

我正在使用CADisplayLink為10個不同的按鈕設置動畫,但這些按鈕都聚集在一起。 所以我的問題是如何實現延遲以使每個按鈕在不同的時間生成動畫,這樣它們就不會全部聚集在一起。

var buttons:[UIButton] = Array()

override func viewDidLoad() {
    super.viewDidLoad()

    var displayLink = CADisplayLink(target: self, selector: "handleDisplayLink:")
    displayLink.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)

    for index in 0...10 - 1{

        buttons.append(UIButton.buttonWithType(.System) as UIButton)

        var xLocation:CGFloat = CGFloat(arc4random_uniform(300) + 30)

        buttons[index].frame = CGRectMake(xLocation, 10, 100, 100)
        buttons[index].setTitle("Test Button \(index)", forState: UIControlState.Normal)
        buttons[index].addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)

        self.view.addSubview(buttons[index])

    }



}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}

func handleDisplayLink(displayLink: CADisplayLink) {

    for index in 0...10 - 1{

        var buttonFrame = buttons[index].frame
        buttonFrame.origin.y += 1
        buttons[index].frame = buttonFrame
        if buttons[index].frame.origin.y >= 500 {
            displayLink.invalidate()
        }
    }
}


func buttonAction(sender: UIButton) {
    sender.alpha = 0
}

要使用延遲進行動畫,您只需使用UIView.animateWithDuration函數而不是CADisplayLink 例如

override func viewDidLoad() {
    for index in 0...10 - 1{

        buttons.append(UIButton.buttonWithType(.System) as UIButton)

        var xLocation:CGFloat = CGFloat(arc4random_uniform(300) + 30)

        buttons[index].frame = CGRectMake(xLocation, 10, 100, 100)
        buttons[index].setTitle("Test Button \(index)", forState: UIControlState.Normal)
        buttons[index].addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)

        self.view.addSubview(buttons[index])

        // Change this line to change the delay between the button animations.
        let delay : NSTimeInterval = 1.0 * NSTimeInterval(index) 

        UIView.animateWithDuration(2.0, delay: delay, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in

            var buttonFrame = self.buttons[index].frame
            buttonFrame.origin.y = 500
            self.buttons[index].frame = buttonFrame


        }, completion: { (finished) -> Void in

        })

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM