【问题标题】:swift ios change uilabel text value over and overswift ios一遍又一遍地更改uilabel文本值
【发布时间】:2016-11-24 21:14:01
【问题描述】:

我有两个变量:

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 吗?

【问题讨论】:

  • 发布你的计时器代码。

标签: ios swift xcode


【解决方案1】:

你需要一个变量来跟踪当前文本是什么,然后是一个 5 秒的计时器,它可以在两个选项之间切换,这可以在 Swift 3 中像这样非常简单地编写。

var isTextOne = true

let timer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) {
    myLabel.text = isTextOne ? textTwo:textOne
    isTextOne = !isTextOne
}

更新为了与 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)

【讨论】:

  • 这是一个很好、干净的答案。 (已投票)iOS 10 中新的基于闭包的 Timer 对象很棒。 Apple 是时候添加基于块/关闭的计时器了。他们应该在 iOS 4 中引入块时就这样做了。
  • @user2636197 iOS 10、macOS 10.12、watchOS 3。我现在将编辑答案以包含旧方法。
【解决方案2】:

您可以通过使用计时器或同步调度队列来完成此操作。

例如,您可以使用以下代码,使用同步调度队列方法每五秒运行一次任务。

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.
    }
}

【讨论】:

    【解决方案3】:

    每 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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多