2016-04-16 62 views
-1

我有一個UIPageViewController,其中每個VC的中心都有一個數字。向上/向下數字動畫計數

我想,當我從視圖中查看刷卡,數量將在0開始和計數,直到它得到正確的號碼(或者,如果數字爲負 - 倒計時)就像這個GIF:

https://d13yacurqjgara.cloudfront.net/users/345970/screenshots/2126044/shot.gif

我該怎麼做?

謝謝!

+1

https://github.com/dataxpress/UICountingLabel 試試這個 –

+0

@ khuong291我已經嘗試了'while'語句添加到標籤1每一次,但沒有奏效 –

+0

@matiboo謝謝!那就是我正在搜索的內容 –

回答

1

您可以使用NSTimer來實現這一點。

這是我爲您創建的示例項目。在ViewController

enter image description here

然後做像這樣:

這樣創建佈局

import UIKit 

class ViewController: UIViewController { 

    @IBOutlet var countingLabel: UILabel! 
    var number = 0 
    var destinationNumber = 30 
    var timer: NSTimer! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 


    @IBAction func startButtonTapped(sender: AnyObject) { 
     timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "countUp", userInfo: nil, repeats: true) 
    } 

    func countUp() { 
     if number < destinationNumber { 
      number += 1 
      countingLabel.text = "\(number)" 
     } else { 
      timer.invalidate() 
     } 
    } 
} 

它將工作。

+0

您需要在完成該操作後使該NSTimer無效 – Hamish

+0

爲什麼?如果我不使它無效,在這種情況下會發生什麼? – Khuong

+0

它將繼續被運行循環調用,這是毫無意義和浪費的。此外,如果多次調用'startButtonTapped',則會在運行循環中添加多個定時器,這也會造成浪費,並可能導致不希望的結果。 – Hamish