gpt4 book ai didi

objective-c - NSViewController 中的第一响应者

转载 作者:太空狗 更新时间:2023-10-30 03:52:56 25 4
gpt4 key购买 nike

我有两个类(class)。 ManagingViewController 是 NSViewController 的子类,ViewController 是 ManagingViewController 的子类。在 Viewcontroller 中,我有一个 NSTextField,我想成为第一个响应者,但我没有做到这一点。

所以它与 Hillegass 的书 Cocoa Programming for Mac OS X (Download of the book's examples) 中的第 29 章几乎相同,除了一个设置为 firstResponder 的 NSTextField。

谁能告诉我正确的方法?

最佳答案

您需要使用-[NSWindow makeFirstResponder:]将文本字段设置为第一响应者。

因为这是一个 NSWindow 方法,只有在您将相应的 View 添加到窗口后,即在您将 View 作为 subview 添加到窗口 View 层次结构中后,它才有意义.在本书的示例中,当您将 View 设置为窗口内框的内容 View 时,就会发生这种情况。例如:

- (void)displayViewController:(ManagingViewController *vc) {
// Try to end editing
NSWindow *w = [box window];


// Put the view in the box
NSView *v = [vc view];
[box setContentView:v];

// Set the first responder
if ([vc class] == [ViewController class]) {
[w makeFirstResponder:[(ViewController *)vc myTextField]];
}
}

这假设 ViewController 公开了一个名为 -myTextField 的 getter 方法。

您可以通过让您的 View Controller 公开一个方法来使它更通用,该方法返回 View Controller 推荐为第一响应者的对象。像这样的东西:

@interface ManagingViewController : NSViewController

- (NSResponder *)recommendedFirstResponder;
@end

@implementation ManagingViewController

- (NSResponder *)recommendedFirstResponder { return nil; }
@end

并且,在 ManagingViewController 的具体子类中,让 -recommendedFirstResponder 返回应该是窗口第一响应者的对象:

@implementation ViewController

- (NSResponder *)recommendedFirstResponder { return myTextField; }
@end

完成后,您可以将 -displayViewController: 更改为类似以下内容:

- (void)displayViewController:(ManagingViewController *vc) {
// Try to end editing
NSWindow *w = [box window];


// Put the view in the box
NSView *v = [vc view];
[box setContentView:v];

// Set the first responder
NSResponder *recommendedResponder = [vc recommendedFirstResponder];
if (recommendedResponder) [w makeFirstResponder:recommendedResponder];
}

关于objective-c - NSViewController 中的第一响应者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5266634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com