swiftuistepper

using String with UIStepper - Swift


i have a label and a UIStepper, i need to increase the number of that label without lossing the letters ( Kd ) . my label will be like this "5.000 Kd" and when i increase the number i don't want to loss the ( Kd ) label.

this is my code

import UIKit
import GMStepper

class ViewController: UIViewController {
    
    
    @IBOutlet var stepper: GMStepper!
    @IBOutlet var price: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    
    @IBAction func stepper(_ sender: Any) {
        
        let label = "5.000 Kd" as NSString
        price.text! = String(label.doubleValue * stepper.value)
        
    }
}

Solution

  • If you are hard-coding the string contents of the label, just maintain a numeric value and rebuild the label contents each time that value changes:

    class ViewController: UIViewController {
    
        @IBOutlet var stepper: GMStepper!
        @IBOutlet var priceLabel: UILabel!
        var price: Double = 5.0
        
        @IBAction func stepper(_ sender: Any) {
            let newValue =  price * stepper.value
            //Format the price with 3 decimal places
            let priceString = String(format: "%.3f", newValue) 
    
            Construct a string with the formatted price and " Kd" and put it in the label
            priceLabel.text = "\(priceString) Kd")
        }
    }