【发布时间】:2019-02-04 14:40:22
【问题描述】:
我是 Swift 的初学者。我已经用尽了所有的尝试和错误,需要帮助!!
我正在使用带有自定义单元格的 UITableView 创建一个记分牌项目,该单元格包含一个 UILabel 和一个 UIButton。按下按钮后,UILabel 会增加 1 以模拟玩家的一个点。我无法在 UILabel 中保存积分,因此每次打开应用程序时,该玩家的积分都会保留。我尝试过使用 UserDefaults、结构和委托,但没有任何运气......我可能做错了。我只需要知道什么是正确的方法。
注意:我能够从 UIAlertController 成功保存玩家名称,这样当我打开应用程序时,名称仍然存在,除非我删除它们,但没有任何运气为每个名称本身保存点数,他们仍然是“0”。
当我关闭然后打开应用程序时应该看起来像这样,但它只在应用程序打开时才会这样做:
Scoreboard UITableView - Screenshot
ViewController 代码如下:
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var items = [String]()
@IBOutlet weak var listTableView: UITableView!
@IBAction func addItem(_ sender: AnyObject) {
alert()
}
override func viewDidLoad() {
super.viewDidLoad()
listTableView.dataSource = self
self.items = UserDefaults.standard.stringArray(forKey:"items") ?? [String]()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! PointsCell
cell.textLabel?.text = items[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func saveData() {
UserDefaults.standard.set(items, forKey: "items")
}
func alert(){
let alert = UIAlertController(title: "Add Player", message: "", preferredStyle: .alert)
alert.addTextField{
(textfield) in
textfield.placeholder = " Enter Player Name "
}
let add = UIAlertAction(title: "Add", style: .default)
{
(action) in guard let textfield = alert.textFields?.first else {return}
if let newText = textfield.text
{
self.items.append(newText)
self.saveData()
let indexPath = IndexPath(row: self.items.count - 1, section: 0)
self.listTableView.insertRows(at: [indexPath], with: .automatic)
}
}
let cancel = UIAlertAction(title: "Cancel", style: .cancel) {
(alert) in
}
alert.addAction(add)
alert.addAction(cancel)
present(alert, animated: true, completion: nil)
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
items.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
saveData()
}
}
这是我的自定义单元格代码,称为 PointsCell:
import UIKit
class PointsCell: UITableViewCell {
var winScore = 0
@IBOutlet weak var scoreUILabel: UILabel!
@IBAction func pointButtonPressed(_ sender: Any) {
winScore += 1
scoreUILabel.text = "\(winScore)"
}
}
【问题讨论】:
-
请分享 saveData() 代码
-
好的,我找到了 saveData()。请在将值分配给 self.items 后重新加载 viewDidload() 中的数据,它将修复您的问题
标签: ios swift uitableview userdefaults