首页 > 解决方案 > Change Current Date To One Before / One After - Swift DatePicker

问题描述

I have a date picker. I would like to change the date displayed to a date before or after using gesture control. Ie, when a person swipes left the date goes one day behind and if a person swipes right the date goes one day after. I am not sure how to implement this as I have tried the method below but i get an error stating 'Cannot convert value of type 'UITextField?' to expected argument type'Date'. If someone could help me out or point me in the right direction I would appreciate that a lot! Thanks

View Controller:

    @IBOutlet weak var userDate: UITextField!
    private var datePicker: UIDatePicker?

    override func viewDidLoad() {
        super.viewDidLoad()

        datePicker = UIDatePicker()
        datePicker?.datePickerMode = .date
        datePicker?.addTarget(self, action: #selector(Test.dateChanged(datePicker:)), for: .valueChanged)

        userDate.inputView = datePicker
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "EEEE, MMM d, yyyy"
        let todayDate = dateFormatter.string(from: Date.init())
        self.userDate.text = todayDate
        
        let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(self.handleGesture(gesture:)))
            swipeLeft.direction = .left
            self.view.addGestureRecognizer(swipeLeft)

        let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(self.handleGesture(gesture:)))
            swipeRight.direction = .right
            self.view.addGestureRecognizer(swipeRight)

    }
    
    @objc func handleGesture(gesture: UISwipeGestureRecognizer) -> Void {
        
        if gesture.direction == UISwipeGestureRecognizer.Direction.right {
               print("Swipe Right")
              view.backgroundColor = .black
                // WHERE I WOULD LIKE TO CHANGE THE DATE ONE DAY AFTER
        }
        else if gesture.direction == UISwipeGestureRecognizer.Direction.left {
               print("Swipe Left")
                view.backgroundColor = .yellow
                // WHERE I WOULD LIKE TO CHANGE THE DATE ONE DAY BEFORE
           }
    }

I tried this method but this is where I get the error:

Calendar.current.date(byAdding: .day, value: 1, to: userDate)!

标签: swiftnsdateuidatepickeruiswipegesturerecognizer

解决方案


The function date(byAdding:value:to:options:) expects a date type to be passed as a parameter. You are passing UITextField instead of a date type. I think what you want to do is

Calendar.current.date(byAdding: .day, value: 1, to: datePicker.date)!

推荐阅读