skip to Main Content

I have a UIDatePicker with Inline style (showing as a calendar). I have an endpoint where I get the available dates for a month, so I would like to detect when the month that is showing is changed. I’ve tried all kinds of things, even add a target for the .allEvents event, but nothing seems to trigger it.

Is there a way to do that?

2

Answers


  1. You should attach an IBAction to the valueChanged event for the picker.

    (You could do that in Interface Builder, or by calling addTarget(_:action:for:) on the picker.)

    That action will get called any time the user changes any part of the date. You’d then need to track the previous date and detect a change of month yourself.

    Login or Signup to reply.
  2. If you’re using a view model, you could easily handle this through that:

    Run the below in a Playground to see what I mean:

    final class ViewModel {
    
        var selectedDateChanged: ((Date) -> Void)?
    
        var selectedDate: Date {
            didSet {
                selectedDateChanged?(selectedDate)
            }
        }
    
        init(selectedDate: Date = .now) {
            self.selectedDate = selectedDate
        }
    }
    
    let viewModel = ViewModel()
    viewModel.selectedDateChanged = { date in
        // now you have the fact that it changed
        // and the new value to use, checking the month
        print(date)
    }
    
    viewModel.selectedDate = .now
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search