作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
在我的应用程序中,我有一个标签,当用户点击 View 或摇动 iPhone 时,它会随机更改报价。如果用户双击同一个 View ,它应该将引用保存在 TableView 中。一开始我以为可以用CoreData,但是他不行。现在我正在使用 UserDefaults,现在如果我双击 View ,报价将被保存,但一次只能保存一个。我想要做的是他创建一个列表,其中包含用户双击的所有引号。
这是 doubleTap 对象中的代码:
let savedQuotes = UserDefaults.standard.setValue(quoteLabel.text!, forKey: "saveQuotes")
if let printSavedQuotes = UserDefaults.standard.string(forKey: "saveQuotes"){
print(printSavedQuotes)
}
下面是我在 TableVIew 中使用的代码:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
_ = UserDefaults.standard.string(forKey: "saveQuotes")
return 15
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "QuoteCell", for: indexPath)
if let printSavedQuotes = UserDefaults.standard.string(forKey: "saveQuotes"){
cell.textLabel?.text = "\(printSavedQuotes)"
}
这是问题的图片。
最佳答案
请了解 Swift 中的集合
。您正在寻找的是 Array
类型。表示按特定顺序存储的元素集合的类型。
文档: https://developer.apple.com/documentation/swift/array
现在,当您学习如何将内容保存到数组中时,您可以将此数组连接到您的 tableView
。
最基本的设置是:
var quotes: [String] = ["quote1", "quote2", "quote3"]
在 numberOfRowsInSection
中,您返回 quotes.count
并且在 cellForRow
中你的 cell.textLabel.text == quotes[indexPath.row]
关于ios - 如何在 TableView 中保存数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53118757/
我是一名优秀的程序员,十分优秀!