您链接的文档中有一些相关的部分我认为可能被忽略了。
我复制了以下几行:
如果您决定继续使用 NSTextField,可以通过实现以下 delegate 方法来实现允许 tab 键和/或允许 enter 和 return 键进行换行:
- (BOOL)control:(NSControl*)control textView:(NSTextView*)textView doCommandBySelector:(SEL)commandSelector;
注意:在你的自己的对象中实现这个delegate方法时,你应该将你的对象设置为这个NSTextField的“delegate”。
我将一些我认为可能被遗漏的标注加粗。
此方法在 NSControl.h 中的 NSControlTextEditingDelegate 协议中。因此,它应该由实现NSControlTextEditingDelegate(即NSTextFieldDelegate)的类实现
这样做的一种常见方法是让 ViewController “持有” NSTextField 成为NSTextFieldDelegate。
这是一个非常简单的示例,使用您链接的 Apple 示例代码:
ViewController.h
#import <Cocoa/Cocoa.h>
@interface ViewController : NSViewController <NSTextFieldDelegate>
@end
ViewController.m
#import "ViewController.h"
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)setRepresentedObject:(id)representedObject {
[super setRepresentedObject:representedObject];
// Update the view, if already loaded.
}
- (BOOL)control:(NSControl *)control textView:(NSTextView *)textView doCommandBySelector:(SEL)commandSelector {
BOOL result = NO;
if (commandSelector == @selector(insertNewline:))
{
// new line action:
// always insert a line-break character and don’t cause the receiver to end editing
[textView insertNewlineIgnoringFieldEditor:self];
result = YES;
}
else if (commandSelector == @selector(insertTab:))
{
// tab action:
// always insert a tab character and don’t cause the receiver to end editing
[textView insertTabIgnoringFieldEditor:self];
result = YES;
}
return result;
}
@end
然后将您的 NSTextField 的委托设置为 ViewController
无需添加自定义子类。
或者,您可以将自定义文本字段作为其自己的代表的子类。大致如下:
#import "MyTextFieldSubclass.h"
@interface MyTextFieldSubclass() <NSTextFieldDelegate>
@end
@implementation MyTextFieldSubclass
- (instancetype)init {
self = [super init];
if (self) {
self.delegate = self;
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)coder {
self = [super initWithCoder:coder];
if (self) {
self.delegate = self;
}
return self;
}
- (instancetype)initWithFrame:(NSRect)frameRect {
self = [super initWithFrame:frameRect];
if (self) {
self.delegate = self;
}
return self;
}
- (void)drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];
// Drawing code here.
}
- (BOOL)control:(NSControl *)control textView:(NSTextView *)textView doCommandBySelector:(SEL)commandSelector {
BOOL result = NO;
if (commandSelector == @selector(insertNewline:))
{
// new line action:
// always insert a line-break character and don’t cause the receiver to end editing
[textView insertNewlineIgnoringFieldEditor:self];
result = YES;
}
else if (commandSelector == @selector(insertTab:))
{
// tab action:
// always insert a tab character and don’t cause the receiver to end editing
[textView insertTabIgnoringFieldEditor:self];
result = YES;
}
return result;
}
@end