开发者

NSTextField : How to draw background only when focused

I put a textfield in a window, and I w开发者_开发百科ant the textfield draw background only when focused. I know that all the controls in the window share one field editor. I tried subclass nstextfield and implement becomeFirstResponder and resignFirstResponder. And tried use custom singleton editor for the window .

Any one know how to achieve this?


In the NSWindow ,every textfield or button share one instance of field editor(a singleton NSTextView instance),so when you click the textfield, textfield become firstResponser first,and then quickly pass it to the shared field editor. So when the textfield lost focus ,the resignFirstResponder of the textfield will never be called(because the field editor is the FirstResponder now).

You can look at fieldEditor:forObject: in NSWindow API. http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSWindow_Class/Reference/Reference.html#//apple_ref/occ/instm/NSWindow/fieldEditor:forObject:


SOLUTION: (Thanks , Michael Gorbach) In my window controller

- (id)windowWillReturnFieldEditor:(NSWindow *)sender toObject:(id)anObject
{
    NSText *text = [sender fieldEditor:YES forObject:self];
    if(text&&[anObject isKindOfClass:[MyCustomTextField class]])
    {
        [text setBackgroundColor:[NSColor whiteColor]];
        [text setDrawsBackground:YES];
    }
    return text;
}


I just did this recently, in a tableView. You need to use a custom cell and fieldEditor. Specifically, you need to call setDrawsbackground:YES on the NSText/NSTextView object that is the field editor, and setBackground: to configure your color of choice. There are two places to set up a custom field editor.

One is to implement setUpFieldEditorAttributes: on a custom NSTextFieldCell subclass that you have configured your NSTextField to use, and another is to use the window or window delegate method windowWillReturnFieldEditor:toObject:.

Note that if the first method doesn't work for a particular setting, sometimes you need to use the second, because it gets in earlier in the codepath.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜