2016-11-23 26 views
0

我有兩個變量:迅速IOS改過來的UILabel文本值和超過

var textOne: String = "Some text" 
var textTwo: String = "Some other text" 

現在我想這些值,所以我遍歷他們一遍又一遍地分配給一個UILabel。

例如,對於5秒MyLabel.text = textOne,則它變成MyLabel.text = textTwo然後重新開始,因此標籤中的文本每5秒改變一次。

現在我已經爲兩個功能設置了兩個定時器。

5秒後,該功能將運行:

showTextOne() { 
MyLabel.text = textOne 
} 

後10秒,此功能將運行:

showTextTwo() { 
    MyLabel.text = textTwo 
} 

但這隻會更改標籤兩次,我想保持它之間改變只要顯示當前VC,就會顯示兩個值。

那麼有沒有其他方法來改變兩個值之間的UILabel.text?

+2

安置自己的計時器代碼。 – Avt

回答

4

你需要一個變量來跟蹤目前的案文是什麼,那麼它可以很簡單地這樣寫的斯威夫特3

var isTextOne = true 

let timer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { 
    myLabel.text = isTextOne ? textTwo:textOne 
    isTextOne = !isTextOne 
} 
兩個選項之間切換5秒計時器

UPDATE,可以兼容iOS的前10,watchOS 3,和MacOS 10.12,因爲舊版本不具備的基於塊的定時器:

var isTextOne = true 

func toggleText() { 
    myLabel.text = isTextOne ? textTwo:textOne 
    isTextOne = !isTextOne 
} 

let timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(toggleText), userInfo: nil, repeats: true) 
+0

這是一個很好,乾淨的答案。 (投票)在iOS 10中新的基於閉包的Timer對象非常棒。這是關於蘋果添加基於塊/閉包的定時器的時間。他們應該在iOS 4引入區塊時做到這一點。 –

+0

@jjatie這隻適用於ios10嗎? – user2636197

+0

@ user2636197 iOS 10,macOS 10.12,watchOS 3.我現在編輯答案以包含舊的方式。 – jjatie

0

每10秒運行一次方法的最簡單方法是使用NSTimerrepeats = true

override func viewDidLoad() { 
    super.viewDidLoad() 
    var timer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: #selector(update), userInfo: nil, repeats: true) 
} 

func update() { 
    // Something cool 
} 
0

您可以通過使用定時器或同步調度隊列來完成此操作。

例如,您可以使用以下代碼使用同步調度隊列方法每五秒運行一次任務。

let current = 0 

func display() { 
    let deadline = DispatchTime.now() + .seconds(5) 
    DispatchQueue.main.asyncAfter(deadline: deadline) { 
     if self.current == 0 { 
      MyLabel.text = "Hello world 1." 
      self.current == 1 
     } else if self.current == 1 { 
      MyLabel.text = "Hello World 2." 
      self.current == 0 
     } 
     self.display() // This will cause the loop. 
    } 
}