swiftxcodeuikituistepper

UIStepper - start counting from 1


I have successfully implemented core data and UISteppers. Every time I try to edit a saved record the UI Stepper starts over from 0. Please help me to figure put what additional code I need to retain the already edited value.

    // 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
    }        
}

I have linked core data like so:

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

I also have an edit and delete function.


Solution

  • This function eventually solved my question:

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