2016-11-23 67 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. 
    } 
}