如何使用for-in-loop在CADisplayLink中创建多个对象

时间:2015-03-02 17:49:15

标签: ios iphone swift for-in-loop cadisplaylink

因此,我尝试使用for循环创建10个按钮,并使用CADisplayLink使所有这10个按钮向下移动。问题是我的CADisplayLink只移动其中一个按钮,我想让它移动所有10个按钮。请帮忙!提前谢谢!

var button: UIButton!



override func viewDidLoad() {
    super.viewDidLoad()

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

    for index in 0...10 {

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

        button = UIButton.buttonWithType(UIButtonType.System) as UIButton

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

        self.view.addSubview(button)

        }



}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}

func handleDisplayLink(displayLink: CADisplayLink) {

    for index in 0...10 {

        var buttonFrame = button.frame
        buttonFrame.origin.y += 1
        button.frame = buttonFrame
        if button.frame.origin.y >= 500 {
            displayLink.invalidate()
        }
    }
}


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

}

1 个答案:

答案 0 :(得分:0)

您只能引用您在viewDidLoad中创建的10个按钮之一。使用类型按钮[UIButton]的数组来存储所有10个,然后在CADisplayLink回调期间遍历每个数组。

您的声明将是:

    var buttons: [UIButton] = Array(count: 10, repeatedValue: UIButton.buttonWithType(.System) as! UIButton)

每次引用原始代码中的按钮时,使用数组索引运算符引用for循环的当前索引处的按钮:

buttons[index]

Swift数组概述和标准库引用如下:

所以提供的代码是:

var buttons: [UIButton] = Array(count: 10, repeatedValue: UIButton.buttonWithType(.System) as! UIButton)

override func viewDidLoad() {
    super.viewDidLoad()

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

    for index in 0...10 {

        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 {

        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
}