0

我的 XIB 文件中有一个文本字段标签,用于显示一些我想要动态加载的文本。这是我的应用程序的当前流程:

- 在 XIB 文件中,文本字段设置为静态文本 - 运行应用程序时,窗口会加载文本字段和静态文本 - 加载后,调用 windowDidLoad 并将文本更改为动态文本

- (void)windowDidLoad
{
    [super windowDidLoad];

    NSDate *currentDate = [NSDate date];
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:currentDate];
    [myTextField setStringValue:[NSString stringWithFormat:@"Year: %ld", [components year]]];
}

不幸的是,在更改文本之前有一点延迟。将文本字段初始化为动态的最佳方法是什么?所以 myTextField 不必初始化为静态文本。

4

1 回答 1

1

You could create an NSTextField subclass, override the awakeFromNib method and put your code there... Here's some (untested) code:

// MyDateTextField.h

@interface MyDateTextField : NSTextField

@end



// MyDateTextField.m

@implementation MyDateTextField

- (void)awakeFromNib {
    NSDate *currentDate = [NSDate date];
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:currentDate];
    [myTextField setStringValue:[NSString stringWithFormat:@"Year: %ld", [components year]]];
}

@end

Alternatively, you could post an NSNotification in the awakeFromNib method, and pick it up in your controller... That might be better design, depending on how much you need your text field to do.

于 2013-07-15T08:37:15.847 回答