UIStepper - 从 1 开始计数

UIStepper - start counting from 1

我已成功实施核心数据和 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")
        }
    }

我还有编辑删除功能

我已经设法添加以下代码来记住步进器中的值。

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")))
}

我遇到的唯一问题是,如果我编辑第二个项目,它会记住第一个项目的值。不知何故,它不记得项目的原始价值。

这个函数最终解决了我的问题:

@IBAction func counterStepperPressed(_ sender: UIStepper) {
    let initialValue=Int(counterTF.text) ?? 0
    let newValue=Int(sender.value)+initialValue
    counterTF.text="\(newValue)"
}