gpt4 book ai didi

ios - 如何让数组一一显示在标签上

转载 作者:行者123 更新时间:2023-11-30 11:45:45 25 4
gpt4 key购买 nike

我试图让数组中的单词一次在标签上显示一个,但是使用我的代码,数组中的最后一个单词会显示出来。我想要的是我的标签显示Hello[wait](最好在某个时间调整一定的时间)World[wait]测试[wait] 数组

这是我的代码:

import UIKit

// Variables
let stringOfWords = "Hello World. Say Hello. Test Number One."
let stringOfWordsArray = stringOfWords.components(separatedBy: " ")

class ViewController: UIViewController {
// Outlets
@IBOutlet weak var labelWords: UILabel!


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

for word in stringOfWordsArray {
labelWords.text=(word)
}
}
}

我希望能够有一个调节器来调节单词显示的速度以及开始和停止按钮。如果有人可以帮助我完成主要部分,那就太好了。

最佳答案

最简单的方法是使用计时器,这样您就可以调用启动/停止它并调整时间(在下面的示例中为 2 秒):

var timer: Timer?
var wordIndex = 0

override func viewDidLoad() {
super.viewDidLoad()
timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(update), userInfo: nil, repeats: true)
}

@objc func update() {
label.text = stringOfWordsArray[wordIndex]
if wordIndex < (stringOfWordsArray.count - 1) {
wordIndex += 1
}
else {
// start again ...
wordIndex = 0
}
}

@IBAction func startAction(_ sender: Any) {
timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(update), userInfo: nil, repeats: true)
}

@IBAction func stopAction(_ sender: Any) {
// remember to invalidate and nil it when you leave view
timer?.invalidate()
timer = nil;
}

关于ios - 如何让数组一一显示在标签上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48844720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com