在Objective-C中,我试图创建一个NSTextField,当单击时,打开一张带有在文本字段下滑出的NSDatePicker的工作表。您可以选择关闭工作表的日期,并使用所选日期填充NSTextField。
我在Swift中找到了关于如何使用协议来执行此操作的文章。 http://www.knowstack.com/swift-nsdatepicker-sample-code/#comment-20440
但是当我将其转换为Objective-C时,我遇到了一些问题。
我第一次点击我的按钮来触发工作表时,工作表会出现在屏幕中间,忽略该事件:
-(NSRect)window:(NSWindow *)window willPositionSheet:(NSWindow *)sheet usingRect:(NSRect)rect {
当我选择一个日期时,主xib中的文本字段会随着选择而更新,因此协议部分正在工作,但工作表在屏幕上仍然没有响应。
如果我再次单击该按钮,则无响应的工作表将关闭并重新出现在NSTextField下,并在我选择日期时自行解除。这是预期的行为。
我的问题是,为什么第一次单击按钮时这不起作用但只能第二次使用?
以下是代码:
#import <Cocoa/Cocoa.h>
@protocol DatePickerProtocol
@required
-(void) selectedDate:(NSDate *)date;
@optional
@end
@interface datePickerWindowController : NSWindowController {
id delegate;
}
-(void)setDelegate:(id)newDelegate;
@end
#import "datePickerWindowController.h"
@interface datePickerWindowController ()
@property (weak) IBOutlet NSDatePicker *datePicker;
@end
@implementation datePickerWindowController
- (void)windowDidLoad {
[super windowDidLoad];
self.datePicker.dateValue = [NSDate date];
}
-(void)setDelegate:(id)newDelegate {
delegate = newDelegate;
NSLog(@"delegate has been set in datePickerWindowController");
}
- (IBAction)selectDate:(NSDatePicker *)sender {
[delegate selectedDate:self.datePicker.dateValue];
[self.window close];
}
@end
#import <Cocoa/Cocoa.h>
#import "datePickerWindowController.h"
@interface AppDelegate : NSObject <NSApplicationDelegate, DatePickerProtocol, NSWindowDelegate>
@end
#import "AppDelegate.h"
@interface AppDelegate ()
@property (weak) IBOutlet NSWindow *window;
@property (weak) IBOutlet NSDatePicker *timePicker;
@property (weak) IBOutlet NSTextField *textDate;
@property (retain) datePickerWindowController * myDatePickerWindowController;
@end
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
self.window.delegate = self;
[self.window setDelegate:self];
self.textDate.stringValue = [NSString stringWithFormat:@"%@",[NSDate date]];
datePickerWindowController * windowController = [[datePickerWindowController alloc] initWithWindowNibName:@"datePickerWindowController"];
self.myDatePickerWindowController = windowController;
self.myDatePickerWindowController.delegate = self;
[self.myDatePickerWindowController setDelegate:self];
}
- (void)applicationWillTerminate:(NSNotification *)aNotification {
}
-(void)selectedDate:(NSDate *)date {
self.textDate.stringValue = [NSString stringWithFormat:@"%@", date];
}
- (IBAction)pickDateButton:(NSButton *)sender {
[self.window beginSheet:self.myDatePickerWindowController.window completionHandler:nil];
}
// Position sheet under text field
-(NSRect)window:(NSWindow *)window willPositionSheet:(NSWindow *)sheet usingRect:(NSRect)rect {
if (sheet == self.myDatePickerWindowController.window) {
NSRect r = self.textDate.frame;
r.origin.y = r.origin.y + 5;
return r;
} else {
return rect;
}
}
@end
我假设我让代表搞砸了。也许在xib或代码中。我不知道为什么它第二次工作。这是由于保留或我如何保持DatePicker。
非常感谢您的帮助。