The NSDatePicker date change method runs twice! (Mac app)

I simply add one NSDatePicker to the form, set the style to graphic, and set the action as follows:

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

in the method, it just prints the selected date.

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

It works, but is executed twice when you click the date in this datepicker parameter. 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
+3
source share
3 answers

Do this to fix this:

- (void) awakeFromNib {
  [datePickerControl sendActionOn:NSLeftMouseDown];  
}
+3
source

The first answer does not work for me. I am using 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 this is a little strange, the action is now called on mouseDown instead of mouseUp, but now it does not matter to me ...)

+2
source

Swift 4 NSDatePicker 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)
  }
}
+1

All Articles