在 swift4 中保存标签文本



我目前正在开发一个iOS应用程序,我将在其中跟踪我们的仓库库存。这是一个非常简单的应用程序,只包含一个标签和一个步进器。该应用程序几乎已完成,但我不知道如何保存标签的更改值。我想自动保存它,以便当有人按步进器上的"+"时,该值应该在不按额外的保存按钮的情况下保存

当前代码:

//montageplatte
@IBOutlet weak var lbl_montageplatte: UILabel!
@IBAction func stepper_montageplatte(_ sender: UIStepper)
{
lbl_montageplatte.text = Int(sender.value).description
}

您可以将其保存在UserDefaults中。

@IBAction func stepper_montageplatte(_ sender: UIStepper) {
lbl_montageplatte.text = Int(sender.value).description
UserDefaults.standard.set(String(sender.value), forKey: "lblMontageplatte")
}

要取回价值,您可以执行以下操作...

if let lblValue = UserDefaults.standard.object(forKey: "lblMontageplatte") as? String {
print(lblValue)
lbl_montageplatte.text = lblValue
}

简单的解决方案:

在自定义单元格中,为步进器和NSKeyValueObservation属性创建插座

@IBOutlet weak var stepper : UIStepper!
var stepperObservation : NSKeyValueObservation?

在控制器cellForRow中添加键值观察器

cell.stepperObservation = cell.stepper.observe(.value, options: [.new]) { (stepper, change) in
print(change.newValue!)
}

而不是打印新值,请更新模型(特定索引路径的项(并在必要时保存数据源数组。

最新更新