iosswiftuistepper

Change Date Using UIStepper


I am trying to figure out a way to allow a user to change current date represented as a label.

The change/action button is a UIStepper.

The label is defaulting to the current date and when they click the stepper they should be able to change the date to tomorrow, next day, and so on when they click the + on the stepper. Then the opposite for clicking - on the stepper.

class DateTestViewController: UIViewController {
    @IBOutlet weak var stepperOutlet: UIStepper!
    @IBOutlet weak var dateLabel: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        let now = NSDate()
        var daysToAdd: Double = 1
        var newDate = now.dateByAddingTimeInterval(60*60*24*daysToAdd)
        dateLabel.text = "\(newDate)"
    }

    @IBAction func stepperAction(sender: AnyObject) {
        var unitsValue = 
        dateLabel.text = "\(unitsValue)"
        
    }
}

Can someone please point me in the right direction to solve this issue?


Solution

  • update: Xcode 8 • Swift 3 or later

    You can use Calendar method date(byAdding unit) to add or subtract the value from your UIStepper from your date as follow:

    import UIKit
    
    class ViewController: UIViewController {
    
        @IBOutlet weak var strDate: UILabel!
        var selectedDate: Date!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            selectedDate = Date()   // sets the initial date
            strDate.text = selectedDate.formatted
        }
    
        @IBAction func stepAction(_ sender: UIStepper) {
            selectedDate = Calendar(identifier: .gregorian).date(byAdding: .day, value: Int(sender.value), to: Date())!
            strDate.text =  selectedDate.formatted
        }
    }
    

    extension Date {
        var formatted: String {
            let df = DateFormatter()
            df.locale = Locale(identifier: "en_US_POSIX")
            df.dateFormat = "MMMM dd, yyyy - EEEE"
            return df.string(from: self)
        }
    }
    

    enter image description here