Home > OS >  How to save user preference of dark or light mode
How to save user preference of dark or light mode

Time:02-04

I have these buttons in my app so user can switch from light to dark mode in the app, how can I save this preference so whichever mode the user selected will still be active the next time they open the app? I'm on Xcode 14.2 Code example please.

@IBAction func darkButton(_ sender: Any) {
        overrideUserInterfaceStyle = .dark
    }

@IBAction func lightButton(_ sender: Any) {
        overrideUserInterfaceStyle = .light
    }

Full code below

import UIKit

class ViewController: UIViewController {

// All Input Texts
@IBOutlet weak var machineODInputText: UITextField!
@IBOutlet weak var pipeODInputText: UITextField!
@IBOutlet weak var pipeLengthInputText: UITextField!
@IBOutlet weak var driveLengthInputText: UITextField!
@IBOutlet weak var muckUpInputText: UITextField!
@IBOutlet weak var jackingSpeedInputText: UITextField!
@IBOutlet weak var weightOfBenoBagInputText: UITextField!
@IBOutlet weak var noOfBenoBagsInputText: UITextField!
@IBOutlet weak var benoQtyForTanksInputText: UITextField!
@IBOutlet weak var noOfBenoBagsPerPalletInputText: UITextField!

// All Result Texts
@IBOutlet weak var lubricationPumpSpeedResult: UILabel!
@IBOutlet weak var volumePerMeterResult: UILabel!
@IBOutlet weak var volumePerPipeResult: UILabel!
@IBOutlet weak var volumeForDriveResult: UILabel!
@IBOutlet weak var benoQtyForLubricationResult: UILabel!
@IBOutlet weak var benoQtyForDriveResult: UILabel!
@IBOutlet weak var noOfPalletsForDriveResult: UILabel!


// All Buttons
@IBAction func lightButton(_ sender: Any) {
    overrideUserInterfaceStyle = .light
    UserDefaults.standard.set("light", forKey: "mode")
}
@IBAction func darkButton(_ sender: Any) {
    overrideUserInterfaceStyle = .dark
    UserDefaults.standard.set("dark", forKey: "mode")
}

@IBAction func calculateButton(_ sender: Any) {
    
    let formatter = NumberFormatter()
    formatter.numberStyle = .decimal
    formatter.maximumFractionDigits = 0
    
    let formatter2 = NumberFormatter()
    formatter2.numberStyle = .decimal
    formatter2.maximumFractionDigits = 2
    
    let pi = Double.pi / 4
    
    let TBMOD = (Double(machineODInputText.text!) ?? 1) / 1000.0
    let pipeOD = (Double(pipeODInputText.text!) ?? 1) / 1000.0
    let muckup = (Double(muckUpInputText.text!) ?? 2.5)
    let advanceSpeed = (Double(jackingSpeedInputText.text!) ?? 1)
    let volPerPipe = (Double(pipeLengthInputText.text!) ?? 1)
    let volForDrive = (Double(driveLengthInputText.text!) ?? 1)
    let noOfBenoBagsForLub = (Double(noOfBenoBagsInputText.text!) ?? 1)
    let weightOfEachBenoBag = (Double(weightOfBenoBagInputText.text!) ?? 1)
    let amountOfBenoBagsInTamks = (Double(benoQtyForTanksInputText.text!) ?? 1)
    let noOfBenoBagsPerPallet = (Double(noOfBenoBagsPerPalletInputText.text!) ?? 1)

    // Calculate Volume per Meter (Ltr per meter)
    let volPerMtrResults1 = ((pi * (TBMOD) * (TBMOD)) - (pi * (pipeOD) * (pipeOD))) * muckup * 1000
    let volPerMtrResult = formatter.string (from: NSNumber(value: volPerMtrResults1))
    volumePerMeterResult.text =  volPerMtrResult

    // Calculate Lubrication Pump Capacity (Ltr per min)
    let pumpCapacityResults1 = (advanceSpeed / 1000) * volPerMtrResults1
    let lubPerMtrResult = formatter.string(from: NSNumber(value: pumpCapacityResults1))
    lubricationPumpSpeedResult.text = lubPerMtrResult

    // Calculate Volume per pipe (M³ per pipe)
    let volPerPipeResults1 = (volPerMtrResults1 / 1000) * volPerPipe
    let volPerPipeResult = formatter2.string(from: NSNumber(value: volPerPipeResults1))
    volumePerPipeResult.text = volPerPipeResult
    
    // Calculate Volume for drive (M³ for drive)
    let volPerDriveResults1 = (volPerMtrResults1 / 1000) * volForDrive
    let volPerDriveResult = formatter.string(from: NSNumber(value: volPerDriveResults1))
    volumeForDriveResult.text = volPerDriveResult
    
    // Calculate Amount of beno for lubrication
    let ammountOfBenoForLubResults1 = noOfBenoBagsForLub * volPerDriveResults1 * weightOfEachBenoBag
    let ammountOfBenoForLubResult = formatter.string(from: NSNumber(value: ammountOfBenoForLubResults1))
    benoQtyForLubricationResult.text = ammountOfBenoForLubResult
    
    // Calculate beno quantity for drive
    let amountOfBenoForDriveResults1 = ammountOfBenoForLubResults1   (amountOfBenoBagsInTamks * 1000)
    let amountOfBenoForDriveResult = formatter.string(from: NSNumber(value: amountOfBenoForDriveResults1))
    benoQtyForDriveResult.text = amountOfBenoForDriveResult
    
    // Calculate number of pallets for drive
    let ammountOfBenoPerPalletResults1 = amountOfBenoForDriveResults1 / weightOfEachBenoBag / noOfBenoBagsPerPallet
    let ammountOfBenoPerPalletResult = formatter2.string(from: NSNumber(value: ammountOfBenoPerPalletResults1))
    noOfPalletsForDriveResult.text = ammountOfBenoPerPalletResult
    
    
    UserDefaults.standard.set(machineODInputText.text, forKey: "TBMOD")
    UserDefaults.standard.set(pipeODInputText.text, forKey: "pipeOD")
    UserDefaults.standard.set(muckUpInputText.text, forKey: "muckUp")
    UserDefaults.standard.set(jackingSpeedInputText.text, forKey: "speed")
    UserDefaults.standard.set(pipeLengthInputText.text, forKey: "pipeLength")
    UserDefaults.standard.set(driveLengthInputText.text, forKey: "driveLength")
    UserDefaults.standard.set(noOfBenoBagsInputText.text, forKey: "noOfBenoBags")
    UserDefaults.standard.set(weightOfBenoBagInputText.text, forKey: "weightOfBenoBag")
    UserDefaults.standard.set(benoQtyForTanksInputText.text, forKey: "benoQtyForTanks")
    UserDefaults.standard.set(noOfBenoBagsPerPalletInputText.text, forKey: "benoBagsPerPallet")
    
    }

// Adding toolbar to top of keyboard with "Done" button (toolbar.swift file)
override func viewDidLoad() {
    super.viewDidLoad()
    machineODInputText.inputAccessoryView = toolBar()
    pipeODInputText.inputAccessoryView = toolBar()
    pipeLengthInputText.inputAccessoryView = toolBar()
    driveLengthInputText.inputAccessoryView = toolBar()
    muckUpInputText.inputAccessoryView = toolBar()
    jackingSpeedInputText.inputAccessoryView = toolBar()
    weightOfBenoBagInputText.inputAccessoryView = toolBar()
    noOfBenoBagsInputText.inputAccessoryView = toolBar()
    benoQtyForTanksInputText.inputAccessoryView = toolBar()
    noOfBenoBagsPerPalletInputText.inputAccessoryView = toolBar()
    
}



// load old data into input feilds
override func viewDidAppear(_ animated: Bool) {
    if let a = UserDefaults.standard.object(forKey: "TBMOD") as? String {
        machineODInputText.text = a
    }

    if let a = UserDefaults.standard.object(forKey: "pipeOD") as? String {
        pipeODInputText.text = a
    }
    
    if let a = UserDefaults.standard.object(forKey: "muckUp") as? String {
        muckUpInputText.text = a
    }
    
    if let a = UserDefaults.standard.object(forKey: "speed") as? String {
        jackingSpeedInputText.text = a
    }
    
    if let a = UserDefaults.standard.object(forKey: "pipeLength") as? String {
        pipeLengthInputText.text = a
    }
    
    if let a = UserDefaults.standard.object(forKey: "driveLength") as? String {
        driveLengthInputText.text = a
    }
    
    if let a = UserDefaults.standard.object(forKey: "noOfBenoBags") as? String {
        noOfBenoBagsInputText.text = a
    }
    
    if let a = UserDefaults.standard.object(forKey: "weightOfBenoBag") as? String {
        weightOfBenoBagInputText.text = a
    }
    
    if let a = UserDefaults.standard.object(forKey: "benoQtyForTanks") as? String {
        benoQtyForTanksInputText.text = a
    }
    
    if let a = UserDefaults.standard.object(forKey: "benoBagsPerPallet") as? String {
        noOfBenoBagsPerPalletInputText.text = a
    }
    
    // load dark/light mode last selected by user
    let mode = UserDefaults.standard.string(forKey: "mode")
     if mode == "dark" {
         overrideUserInterfaceStyle = .dark
     } else {
         overrideUserInterfaceStyle = .light
     }
    
    machineODInputText.clearsOnBeginEditing = true
    pipeODInputText.clearsOnBeginEditing = true
    pipeLengthInputText.clearsOnBeginEditing = true
    driveLengthInputText.clearsOnBeginEditing = true
    muckUpInputText.clearsOnBeginEditing = true
    jackingSpeedInputText.clearsOnBeginEditing = true
    weightOfBenoBagInputText.clearsOnBeginEditing = true
    noOfBenoBagsInputText.clearsOnBeginEditing = true
    benoQtyForTanksInputText.clearsOnBeginEditing = true
    noOfBenoBagsPerPalletInputText.clearsOnBeginEditing = true
    
}

}

CodePudding user response:

you can save it in UserDefaults as follows.

@IBAction func darkButton(_ sender: Any) {
    overrideUserInterfaceStyle = .dark
    UserDefaults.standard.set("dark", forKey: "mode")
}

@IBAction func lightButton(_ sender: Any) {
    overrideUserInterfaceStyle = .light
    UserDefaults.standard.set("light", forKey: "mode")
}

When reopening the application do as follow.

 let mode = UserDefaults.standard.string(forKey: "mode")

 if mode == "dark" {
     overrideUserInterfaceStyle = .dark
 } else {
     overrideUserInterfaceStyle = .light
 }

Where you need to add the above code depends on your scenario. I suggest to add it inside AppDelegate -> didFinishLaunchingWithOptions.

  • Related