开发者

NSDatePicker change date method runs twice!(mac app)

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


Do this to fix this:

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


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...)


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)
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜