我一直试图创建一个应用程序,该应用程序会在一定时间(即五秒钟)后随机打印一个新单词。
import UIKit
class ViewController: UIViewController {
var myTimer : Timer!
var theValue = 0
@IBOutlet weak var textLabel: UILabel!
@IBOutlet weak var InspireLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib
}
override func viewDidDisappear(_ animated: Bool) {
self.myTimer.invalidate()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@objc func updateMyLabel() {
theValue += 1
self.textLabel.text = String(theValue)
}
func randomText() -> String {
if theValue > 5 {
let words = ["Place", "Cat", "House"]
return words.randomElement() ?? "" //Use default method to get random element from Array
}
return "string if theValue < 5 or equal to 5"
}
@IBAction func ResetButton(_ sender: Any) {
self.myTimer.invalidate()
theValue = 0
self.textLabel.text = String(theValue)
}
@IBAction func PauseButton(_ sender: Any) {
self.myTimer.invalidate()
}
@IBAction func PlayButton(_ sender: Any) {
self.myTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateMyLabel), userInfo: nil, repeats: true)
}
}
这是我现在拥有的所有代码。您可能会说我也是StackExchange的新手,所以请在礼节上的任何违规行为辩解。
答案 0 :(得分:0)
由于您忘记在代码中添加else
部分,因此出现了错误。
func randomText() -> String {
if theValue > 5 {
let words = ["Place", "Cat", "House"]
return words.randomElement() ?? "" //Use default method to get random element from Array
}
return "string if theValue < 5 or equal to 5"
}