5

I just add one NSDatePicker to the form, set the style graphical, and set the action like this:

[datePicker setAction:@selector(datePickSelected:)];

in the method, it just prints out the selected date.

-(void)datePickSelected:(id)sender
{
    NSLog(@"%@",[datePicker dateValue]);
}

It works, but runs two times when you click the date in this datepicker. Why is this?

2011-05-25 15:17:09.382 xxx[6609:a0f] 2011-05-13 15:17:04 +0800
2011-05-25 15:17:09.677 xxx[6609:a0f] 2011-05-13 15:17:04 +0800
Monolo
  • 18,205
  • 17
  • 69
  • 103
vincent
  • 113
  • 8
  • I'm having exactly the same problem. No idea what is causing it. – Kenny Wyland Oct 10 '11 at 18:55
  • May I ask why you didn't create it in IB and connect it graphically? Does this problem occur then as well? Would be interesting, I assume. – pbx Jun 13 '12 at 19:14

3 Answers3

3

Do this to fix this:

- (void) awakeFromNib {
  [datePickerControl sendActionOn:NSLeftMouseDown];  
}
strange
  • 9,654
  • 6
  • 33
  • 47
  • `NSLeftMouseDown` is deprecated in 10.12. Should use this `[datePicker sendActionOn: NSEventMaskLeftMouseDown];` – Z S Dec 14 '16 at 07:02
3

Here's a Swift 4 solution with the NSDatePicker inside an NSViewController:

class DatePickerVC: NSViewController{

  @IBOutlet weak var datePicker: NSDatePicker!
  var date:Date!

  override func viewDidLoad() {
    super.viewDidLoad()

    self.datePicker.target = self
    self.datePicker.action = #selector(dateSelected)

    let action = NSEvent.EventTypeMask.mouseExited
    self.datePicker.sendAction(on: action)
  }

  @objc func dateSelected(){
    print(datePicker.dateValue)
  }
}
Clifton Labrum
  • 13,053
  • 9
  • 65
  • 128
2

The first answer doesn't work for me. I use this now in Swift:

override func awakeFromNib() {
    self.datePicker.target = self
    self.datePicker.action = Selector("dateSelected:")
    let action = Int(NSEventMask.MouseExitedMask.rawValue)
    self.datePicker.sendActionOn(action)
}

(But it's a little bit strange, the action is now called on mouseDown instead of mouseUp, but that doesn't matter for me now...)

Lupurus
  • 3,618
  • 2
  • 29
  • 59