トップページドキュメント > テキストの入力と描画

NSTextFieldCellの利用

フィールドエディターを利用することで、ウィンドウ内に複数のテキストフィールドが配置されている場合でも、効率よくテキストを編集できるようになりました。しかし、フィールドエディターをセットアップするのは、とても手間のかかる作業です。特に、フィールドエディターは複数のオブジェクト間で共有され、しかもフレームワーク側で再初期化されることはないため、セットアップを必要最小限にとどめることもできず、常に全ての項目を設定しなければなりません。

そこで、実際にフィールドエディターを使用するときは、NSTextFieldCellにセットアップを全て任せてしまう方法を取ります。

NSTextFieldCellオブジェクトは、ビューのインスタンス変数として持ち、initWithFrame:内で生成と初期化を行います。このとき、初期化処理については、必要最小限のもので済ませることができます。

@interface MyTextCellView : NSView
{
    NSTextFieldCell* textField;
}
@end



@implementation MyTextCellView

- (id)initWithFrame:(NSRect)frameRect
{
    if(!(self = [super initWithFrame:frameRect])) return nil;
	
    textField = [[NSTextFieldCell alloc] initTextCell:@""];
    [textField setTextColor:[NSColor controlTextColor]];
    [textField setBackgroundColor:[NSColor controlBackgroundColor]];
    [textField setBordered:YES];
    [textField setBezeled:YES];
    [textField setDrawsBackground:YES];
    NSFont* font = [NSFont fontWithName:@"HiraMinPro-W3" size:12.0];
    [textField setFont:font];
    [textField setEditable:YES];
    [textField setScrollable:YES];
    [textField setSelectable:YES];
	
    return self;
}

@end

テキストの描画

テキストの描画は、NSTextFieldCelldrawWithFrame:inView:メソッドを呼ぶことで行います。描画する矩形を指定するだけで、テキストだけでなく、drawsBackgroundプロパティをYESにしていれば背景も描画することができます。

- (void)drawRect:(NSRect)rect
{
    [textField drawWithFrame:[self bounds] inView:self];
}

テキストの編集

NSTextFieldCellを利用してテキストを編集する場合、フィールドエディターの取り扱いはこれまでどおりですが、手間のかかるセットアップ作業をNSTextFieldCelleditWithFrame:inView:editor:delegate:event:メソッドに全てやらせることができます。

- (void)mouseDown:(NSEvent*)theEvent
{
    [[self window] endEditingFor:self];
    NSText* fieldEditer = [[self window] fieldEditor:YES forObject:self];
    [textField editWithFrame:[self bounds]
                      inView:self
                      editor:fieldEditer
                    delegate:self
                       event:theEvent];
}

フィールドエディターのデリゲートには、ビュー自身を設定します。そのため、編集の終了処理もこれまでどおり、textDidEndEditing:メソッドを実装して行います。

- (void)textDidEndEditing:(NSNotification *)aNotification
{
    NSText* fieldEditer = [[self window] fieldEditor:YES forObject:self];
    NSString* text = [NSString stringWithString:[fieldEditer string]];
    [textField setStringValue:text];
    [textField endEditing:fieldEditer];
    [self setNeedsDisplay:YES];
}

最後に、NSTextFieldCellendEditing:メソッドを呼ぶことで、編集の後始末をすることができます。

Copyright(C)2001-2010 STRIPE-NET. All Right Reserved.