47

I noticed that there is no delegate to observe changes in UIDatePicker. Is there a way to detect when a change is made in the picker without confirming anything, like the moment it spins and lands on a new number I want to be able to detect that. I thought about key value observing, but I don't think there's a property that changes on the spot

Chris
  • 7,270
  • 19
  • 66
  • 110

4 Answers4

70

You need to add to your UIDatePicker the UIControlEventValueChanged event to handle date changes:

[myDatePicker addTarget:self action:@selector(dateIsChanged:) forControlEvents:UIControlEventValueChanged];

Then the implementation:

- (void)dateIsChanged:(id)sender{
     NSLog(@"Date changed");
}
chroman
  • 1,534
  • 12
  • 18
  • 1
    Good answer, I'm too lazy for this programmatic stuff. Note that you'd need a reference to the date picker to do this, which you wouldn't necessarily have if you created it in IB (although you could easily add it). – Dustin Aug 08 '12 at 14:43
  • 3
    Swift version: `picker.addTarget(self, action: #selector(dateChanged), forControlEvents: .ValueChanged) @objc func dateChanged(sender: UIDatePicker) { print(sender.date.description) }` – Alexander Bekert Mar 29 '16 at 18:51
45

Go to IB and drag from the UIDatePicker to your .h file. Then selectenter image description here

Handle this however you want in your .m file; XCode will add the method below for you.

enter image description here

Dustin
  • 6,783
  • 4
  • 36
  • 53
11

Swift 4.2 | Xcode 10.1

@objc func handleDatePicker(_ datePicker: UIDatePicker) {
    textField.text = datePicker.date.formatted
}

override func viewDidLoad() {
    super.viewDidLoad()
    datePicker.addTarget(self, action: #selector(handleDatePicker), for: .valueChanged)
}

extension Date {
    static let formatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "EEEE, dd MMM yyyy HH:mm:ss Z"
        return formatter
    }()
    var formatted: String {
        return Date.formatter.string(from: self)
    }
}
Argus
  • 2,241
  • 1
  • 22
  • 27
2

Here is a proposal for a KVO-compliant date picker:

@interface LNKVODatePicker : UIDatePicker

@end

@implementation LNKVODatePicker

- (void)willMoveToWindow:(UIWindow *)newWindow
{
    [super willMoveToWindow:newWindow];

    [self removeTarget:self action:@selector(_didChangeDate) forControlEvents:UIControlEventValueChanged];

    if(newWindow != nil)
    {
        [self addTarget:self action:@selector(_didChangeDate) forControlEvents:UIControlEventValueChanged];
    }
}

- (void)dealloc
{
    [self removeTarget:self action:@selector(_didChangeDate) forControlEvents:UIControlEventValueChanged];
}

- (void)_didChangeDate
{
    [self willChangeValueForKey:@"date"];
    [self didChangeValueForKey:@"date"];
}

@end
Léo Natan
  • 56,823
  • 9
  • 150
  • 195