【问题标题】:How to set up a delay in a CADisplayLink如何在 CADisplayLink 中设置延迟
【发布时间】:2015-03-04 01:38:04
【问题描述】:

我正在使用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
}

【问题讨论】:

  • 为什么不用普通视图动画呢?它更简单,您可以获得一个内置的延迟参数。

标签: ios swift delay cadisplaylink


【解决方案1】:

要制作延迟动画,您可以只使用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

        })

    }
}

【讨论】:

  • 这就是我最初所做的,但现在你无法点击没有 CADisplayLink 的动画按钮
  • 点击动画按钮很棘手,但可能。你有没有发布过关于这个的问题?问题是您需要进行自己的点击测试,因为按钮认为它已经在其最终位置。
  • 您可以检查此答案以启用动画 UIButton 上的用户交互。 stackoverflow.com/questions/8346100/…
猜你喜欢
  • 1970-01-01
  • 2013-03-30
  • 1970-01-01
  • 2022-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-26
  • 2023-03-13
相关资源
最近更新 更多