在 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。
非常感谢您的帮助。