优化int递增

时间:2015-10-14 09:31:36

标签: ios swift swift2

我有以下代码让UILabel增加动画。 (从0到x值)

var i:Int = 0;
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    animateIncrementUILabel(counterLabelOne, labelValue: 30)
    animateIncrementUILabel(counterLabelTwo, labelValue: 22)
    animateIncrementUILabel(counterLabelThree, labelValue: 19)
}

func animateIncrementUILabel(label: UILabel, labelValue: Int)
{
    let arr: Array = [label, labelValue]

    NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("update:"), userInfo: arr, repeats: true)
}

func update(timer: NSTimer!)
{
    let arr = timer.userInfo as! NSArray
    let lbl = arr[0] as! UILabel
    let amount = arr[1] as! Int

    if(i > amount)
    {
        timer.invalidate()

    } else {
        lbl.text = String(i)
        i++
    }
}

不知何故,他们的价值在每个标签上都不正确,第一个正确但第二个和第三个错过1或2个加起来。我在这做错了什么?

2 个答案:

答案 0 :(得分:1)

这有效:

class LabelIncrementVC:UIViewController {
    @IBOutlet var label:UILabel!
    @IBOutlet var label2:UILabel!
    @IBOutlet var label3:UILabel!


    override func viewDidLoad() {
        super.viewDidLoad()

        animateIncrementUILabel(label, maxValue: 30)
        animateIncrementUILabel(label2, maxValue: 22)
        animateIncrementUILabel(label3, maxValue: 19)
    }

    func animateIncrementUILabel(label: UILabel, maxValue: Int) {
        let arr:NSMutableArray = [label, maxValue, 0]

        NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "update:", userInfo: arr, repeats: true)
    }

    func update(timer: NSTimer!) {
        let arr = timer.userInfo as! NSMutableArray
        let lbl = arr[0] as! UILabel
        let max = arr[1] as! Int
        var val = arr[2] as! Int

        val++
        lbl.text = String(val)
        if val >= max {
            timer.invalidate()
        }

        arr[2] = val
    }
}

答案 1 :(得分:0)

您需要为每个UILabel使用不同的计数器变量。

如果这些标签是动态的,请使用NSMutableArray计数器。

或者,获取标签上的值以了解下一步的原因:

func animateIncrementUILabel(label: UILabel, labelValue: Int)
{
    let arr: Array = [label, labelValue]

    label.text = String(0)

    NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("update:"), userInfo: arr, repeats: true)
}

func update(timer: NSTimer!)
{
    let arr = timer.userInfo as! NSArray
    let lbl = arr[0] as! UILabel
    let amount = arr[1] as! Int
    let counter = lbl.text.intValue
    if(counter > amount)
    {
        timer.invalidate()

    } else {
        lbl.text = String(counter+1)
    }
}