iOS 应用程序 - 更新每一天的字符串数组



我一直在用 swift 做一个副项目,它基本上是一个日常应用程序。我已经将 30 个单词和内容存储到一个数组中,并且每天都在尝试更新单词。我已经尝试了一些修复程序,但无济于事。即使我更改手机上的日期,我也只能显示第一个数组。

单词数字和单词日期冲突吗?我怎样才能适应它,以便每天弹出一个新词?

let wordList =
[
Words(word: "aaa", pronounciation: "bbbb", type: "noun", definition:"blah"),
Words(word: "bbb", pronounciation: "cccc", type: "adjective", definition:"blah")
]
var wordNumber = 0;

class ViewController: UIViewController {
@IBOutlet weak var wordLabel: UILabel!
@IBOutlet weak var pronounciationLabel: UILabel!
@IBOutlet weak var wordTypeLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
updateWord()
}
@IBAction func prepareForUnwind (segue: UIStoryboardSegue){}
func updateWord()
{
let date = Date()
let dateIndex = Int(date.timeIntervalSince1970) / (60*60*24)
let wordOfDay = wordList[dateIndex % wordList.count]

wordLabel.text = wordList[wordNumber].word
pronounciationLabel.text = wordList[wordNumber].pronounciation
}
}

一个简单的方法是从Calendar获取当天的索引。

由于月份中的某天从 1 开始并且数组索引从零开始,因此您必须减小该值。考虑到几个月有 31 天。

func updateWord()
{
let day = Calendar.current.component(.day, from: Date())
let wordOfDay = wordList[day - 1]
wordLabel.text = wordList[wordNumber].word
pronounciationLabel.text = wordList[wordNumber].pronounciation
}

但是,如果您每天想要一次随机单词,则必须将当前日期的数字和当前的随机索引保存在UserDefaults中。将其加载到viewDidLoad中,并将日期与当前值进行比较。如果两个值相等,则通过保存的索引获取单词。如果它们不相等,则获取一个介于 1 和 31 之间的随机数,并保存当前日期的数字和索引。

我会说在您的数组中存储 31 个值,因为最多可以有 31 天。然后根据今天,显示你今天的话。

func updateWord() {
let currentDay = Calendar.current.component(.day, from: Date()) // this would return the current day in Int, like today is 8th Jan, so it would return 8
let wordOfDay = wordList[currentDay-1] // -1 because array index starts from 0 
wordLabel.text = wordOfDay.word
pronounciationLabel.text = wordOfDay.pronounciation
}

我会尝试几件事:

除非有手动计算日期索引的特定原因,否则请使用:

let calendar = Calendar.current
calendar.component(.day, from: Date()) 

calendar.component(.day, from: Date())返回 Int 的位置

另外,我看到wordList只有两个值。可能是您提交的日期索引超出了wordList的范围。要对此进行测试,请尝试手动输入,如下所示。如果数组索引是问题所在,这应该有效。

wordLabel.text = wordList[0].word

最后,为了提高可读性,执行以下操作可能是有意义的:

let firstWord = Words(word: "aaa", pronounciation: "bbbb", type: "noun", definition:"blah")
let secondWord = Words()
let wordList =
[
firstWord, secondWord, etc.
]

当应用运行时,代码中没有任何内容会实际告诉视图控制器自行刷新,或者再次检查日期并选择另一个单词。

解决这个问题的一种方法可能是viewDidLoad()启动计时器,要么在短时间内重复,要么从午夜开始每 24 小时重复一次。

另一种方法可能是检查日期并仅在用户打开/激活/切换回应用时显示新单词。这可以通过添加观察器来完成,如下所示:

NotificationCenter.default.addObserver(self, selector: #selector(didEnterBackground), name: UIApplication.didBecomeActiveNotification, object: nil)

或者,如果您的应用具有UIWindowSceneDelegate,则如下所示:

if #available(iOS 13.0, *) {
NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive), name: UIScene.didActivateNotification, object: nil)
} else {
NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
}

didBecomeActive函数(或等效函数(中,您可以检查日期并获取另一个随机单词。

最新更新