Cocoa Event Handling Guideを読んで、自分のアプリケーションでキーボード イベントを処理する方法を理解しています。ただし、私が見つけた解決策がこの問題にアプローチするための慣用的な方法なのか、それとも最善の方法なのかはよくわかりません。
(内に)CustomView
と. 基本的にチャットウィンドウ。CustomViewController
NSTextView
NSScrollView
NSTextField
私が望むのは、NSTextField
が選択されていなくても、ユーザーが入力を開始した場合でもNSTextField
、 をファーストレスポンダにし、ユーザーが入力したテキストを に追加する必要があるということNSTextField
です。
私は、イベントをRootWindowController
キャプチャし、最初の応答者を作成し、フィールド エディターを取得し、テキストを追加するソリューション (以下) を考え出しました。keyDown
NSTextField
これはココア開発者が採用する慣用的なアプローチですか、それとも私が見逃しているより単純な方法ですか? コードは以下です。ありがとう。
RootWindowController.m
#import "RootWindowController.h"
@implementation RootWindowController
- (id)initWithWindow:(NSWindow *)window
{
self = [super initWithWindow:window];
if (self) {
self.customViewController = [[CustomViewController alloc] init];
NSView *contentView = self.window.contentView;
CGFloat viewWidth = contentView.frame.size.width;
CGFloat viewHeight = contentView.frame.size.height;
self.customViewController.customView.textField.frame =
NSMakeRect(0, 0, viewWidth, 50);
self.customViewController.customView.scrollView.frame =
NSMakeRect(0, 51, viewWidth, viewHeight - 50);
self.customViewController.customView.textView.frame =
NSMakeRect(0, 51, viewWidth, viewHeight - 50);
self.window.contentView = self.customViewController.customView;
}
return self;
}
- (void)keyDown:(NSEvent *)theEvent
{
[self.window
makeFirstResponder:self.customViewController.customView.textField];
NSString *characters = theEvent.characters;
NSText *fieldEditor = [self.window fieldEditor:YES
forObject:self.customViewController.customView.textField];
[fieldEditor setString:
[NSString stringWithFormat:@"%@%@", fieldEditor.string, characters]];
[fieldEditor setSelectedRange:NSMakeRange(fieldEditor.string.length, 0)];
[fieldEditor setNeedsDisplay:YES];
}
@end
CustomViewController.m
#import "CustomViewController.h"
@implementation CustomViewController
- (id)init
{
self = [super init];
if (self) {
self.customView = [[CustomView alloc] initWithFrame:NSZeroRect];
[self.customView setAutoresizesSubviews:YES];
self.view = self.customView;
}
return self;
}
@end
CustomView.m
#import "CustomView.h"
@implementation CustomView
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.scrollView = [[NSScrollView alloc] initWithFrame:NSZeroRect];
self.textView = [[NSTextView alloc] initWithFrame:NSZeroRect];
self.textField = [[NSTextField alloc] initWithFrame:NSZeroRect];
[self.textView setAutoresizesSubviews:YES];
[self.scrollView setDocumentView:self.textView];
[self.scrollView setHasVerticalScroller:YES];
[self.scrollView setAutoresizesSubviews:YES];
[self.textField setStringValue:@"Placeholder Text"];
[self addSubview:self.scrollView];
[self addSubview:self.textField];
[self.textView setNeedsDisplay:YES];
}
return self;
}
- (BOOL)acceptsFirstResponder
{
return YES;
}
@end