我已经成功地实现了核心数据和UISteppers。每次我尝试编辑保存的记录时,UI步骤从0开始。请帮我计算一下我需要什么额外的代码来保留已经编辑过的值。
// This function adds the stepper to a field
//issue: it does not remember the score when i edit it and starts over
@IBAction func counterStepperPressed(_ sender: UIStepper) {
counterTF.text = Int(sender.value).description
}
@IBAction func pointStepperPressed(_ sender: UIStepper) {
pointTF.text = Int(sender.value).description
}
@IBAction func savingsStepperPressed(_ sender: UIStepper) {
savingsTF.text = Int(sender.value).description
}
}我将核心数据链接如下:
import CoreData
class AktieViewController: UIViewController {
@IBOutlet weak var counterStepper: UIStepper!
@IBOutlet weak var pointsStepper: UIStepper!
@IBOutlet weak var savingsStepper: UIStepper!
var selectedAktie: Aktie? = nil
override func viewDidLoad()
{
super.viewDidLoad()
if(selectedAktie != nil) {
savingsTF.text = selectedAktie?.saving
counterTF.text = selectedAktie?.counter
pointTF.text = selectedAktie?.point
}
}
@IBAction func saveAction(_ sender: Any) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context: NSManagedObjectContext = appDelegate.persistentContainer.viewContext
if(selectedAktie == nil)
{
let entity = NSEntityDescription.entity(forEntityName: "Aktie", in: context)
let newAktie = Aktie (entity: entity!, insertInto: context)
newAktie.saving = savingsTF.text
newAktie.point = pointTF.text
newAktie.counter = counterTF.text
do {
try context.save()
aktieList.append(newAktie)
navigationController?.popViewController(animated: true)
}
catch
{
print("context save error")
}
}我也有一个编辑和删除功能。
发布于 2022-05-07 02:03:25
这个函数最终解决了我的问题:
@IBAction func counterStepperPressed(_ sender: UIStepper) {
let initialValue=Int(counterTF.text) ?? 0
let newValue=Int(sender.value)+initialValue
counterTF.text="\(newValue)"
}发布于 2022-05-05 15:30:28
我已经成功地添加了以下代码来记住步骤中的值。
if let value=UserDefaults.standard.value(forKey: "counterStepper") as? Double {
counterStepper.value=value counterTF.text=String(describing: value)在操作中,我添加了以下代码。
@IBAction func counterStepperPressed(_ sender: UIStepper) {
counterTF.text=String(describing: sender.value)
UserDefaults.standard.setValue(sender.value, forKey: "counterStepper")
NotificationCenter.default.post(Notification.init(name: Notification.Name("StepperDidChangeValue")))
}我唯一的问题是,如果我编辑第二项,它会记住第一项的值。不知何故,它没有记住项目的原始价值。
https://stackoverflow.com/questions/72015983
复制相似问题