ios - 每次按下按钮时随机显示文件中的元素
问题描述
所以我有这个超过600字的大文件。我将它们添加到我的数组中,现在我需要在标签上随机显示它们。每次按下按钮时,都必须显示新的随机词,直到计时器结束。我已经搜索了这个问题的多个来源,但无法应用它们,因为我是新手
import UIKit
class ViewController: UIViewController {
var wordArray: [String] = []
var i: Int = 0
var timer = Timer()
var totalSecond = 5
func startTimer() {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
}
@objc func updateTime() {
if totalSecond != 0 {
totalSecond -= 1
timerLabel.text = "\(totalSecond) seconds left"
} else {
endTimer()
}
}
func endTimer() {
timer.invalidate()
}
func timeFormatted(_ totalSeconds: Int) -> String {
let seconds: Int = totalSeconds % 60
return String(format: "0:%02d", seconds)
}
@IBOutlet weak var timerLabel: UILabel!
@IBOutlet weak var showWordLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let url = Bundle.main.url(forResource: "english_words", withExtension: "txt")!
do {
let string = try String(contentsOf: url, encoding: .utf8)
wordArray = string.components(separatedBy: CharacterSet.newlines)
} catch {
print(error)
}
startTimer()
}
@IBAction func nextBtn(_ sender: UIButton) {
}
}
解决方案
虽然我不是 100% 确定我理解你的问题,但这里是你的 viewController 的修改版本。
请参阅代码中的注释。
class ViewController: UIViewController {
var wordArray: [String] = []
var i: Int = 0
var timer = Timer()
var totalSecond = 5
func startTimer() {
// Stop old timer
timer.invalidate()
// Start new timer
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
}
@objc func updateTime() {
if totalSecond != 0 {
totalSecond -= 1
timerLabel.text = "\(totalSecond) seconds left"
} else {
endTimer()
}
}
func endTimer() {
timer.invalidate()
}
func timeFormatted(_ totalSeconds: Int) -> String {
let seconds: Int = totalSeconds % 60
return String(format: "0:%02d", seconds)
}
@IBOutlet weak var timerLabel: UILabel!
@IBOutlet weak var showWordLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let url = Bundle.main.url(forResource: "english_words", withExtension: "txt")!
do {
let string = try String(contentsOf: url, encoding: .utf8)
wordArray = string.components(separatedBy: CharacterSet.newlines)
} catch {
print(error)
}
startTimer()
}
@IBAction func nextBtn(_ sender: UIButton) {
// Fetch random Word from array
let randomValue = Int.random(in: 0..<wordArray.count)
let randomWord = wordArray[randomValue]
// Assign to label
showWordLabel.text = randomWord
// Restart timer
startTimer()
}
}
推荐阅读
- flutter - Flutter:如何使用具有动态范围滑块的范围模型(或任何状态管理包)?已编辑
- python - 如何使用 js 设置 Access-Control-Allow-Origin
- ios - 如何在 iOS Swift 中使用 Firebase FCM 令牌在 PubNub 上注册推送通知
- stm32 - STM32H7 在 OBFlash 中更改 boot1 地址
- ansible - 如何将我的任务的输出与所需的操作进行比较?
- git - 如何从 Gerrit 中的不同关系链中提取提交
- java - 什么是 java.constructors.single()?
- c++ - 这段 C++ 代码的时间复杂度是多少
- mysql - Laravel 部署到谷歌云应用引擎问题
- c++ - 无捕获 lambda 是结构类型吗?