3

我想实现一个 NSTextField,当我单击它时,它会选择所有文本。(为用户提供删除所有当前文本的简单方法)当我完成编辑它时,通过按 enter/tab 或将鼠标移到它的矩形之外,我会将焦点移出该字段,并将它的 alpha 值更改为0.5。

我的代码:

H 文件:

#import <Foundation/Foundation.h>

@interface MoodMsgTextField : NSTextField<NSTextFieldDelegate>

@end

M 文件:

-(BOOL) becomeFirstResponder
{    
    NSLog(@"become first responder");

    BOOL result = [super becomeFirstResponder];
    if(result)
    {
        [self setAlphaValue:1.0];
        [self performSelector:@selector(selectText:) withObject:self afterDelay:0];
    }
    return result;
}

-(BOOL) refusesFirstResponder
{
    return NO;
}

-(BOOL) resignFirstResponder
{
    NSLog(@"resigning first responder");

    BOOL result = [super resignFirstResponder];

    NSText* fieldEditor = [self.window fieldEditor:YES forObject:self];
    [fieldEditor setSelectedRange:NSMakeRange(0,0)];
    [fieldEditor setNeedsDisplay:YES];

    [self setAlphaValue:0.5];

    return  result;
}

-(void)awakeFromNib
{
    self.delegate = self;

    [self setAlphaValue:0.5];    
    [self setBordered:YES];
    [self setWantsLayer:YES];
    self.layer.borderWidth = 0.5;
    self.layer.borderColor = [[NSColor grayColor] CGColor];        
}

- (void)controlTextDidChange:(NSNotification *)aNotification
{    
    NSLog(@"the text is %@",self.stringValue);
}

- (void)controlTextDidEndEditing:(NSNotification *)aNotification
{
    NSLog(@"end editiing : the text is %@",self.stringValue);
    [self.window makeFirstResponder:nil];
}

- (void)mouseEntered:(NSEvent *)theEvent
{
    [self setWantsLayer:YES];
    self.layer.borderWidth = 0.5;
    self.layer.borderColor = [[NSColor grayColor] CGColor];        
}
- (void)mouseExited:(NSEvent *)theEvent
{
    [self setWantsLayer:YES];
    self.layer.borderWidth = 0;
}

所以,我有几个问题:

1.

当我在 NSTextField 内按下时(当焦点在外面时),它立即变成并辞去第一响应者,我得到编辑结束消息。这是为什么 ?我点击的日志是这样的:

2011-08-02 18:03:19.044 ooVoo[42415:707] become first responder
2011-08-02 18:03:19.045 ooVoo[42415:707] resigning first responder
2011-08-02 18:03:19.104 ooVoo[42415:707] end editing : the text is 

2.

当我按下回车键时,它只会选择里面的所有文本并且不会移动鼠标焦点。当我按下选项卡时,似乎确实移动了焦点,但是两者都不会导致 resignFirstResponder 被调用。为什么 ?

3. 没有一个鼠标事件函数被调用。我需要为此做一些特别的事情吗?我认为既然它们是 NSResponder 的,我会通过从 NSTextField 继承来免费获得它们。我在这里也需要 NSTrackingInfo 吗?

4.

最后但并非最不重要的一点是,由于某种原因,每几个字母,一个字母似乎是粗体。我不知道为什么。

我会很感激任何帮助。谢谢

4

1 回答 1

5
  1. I am not sure why this is happening in this case but you should read about the Field Editor concept. Basically a NSTextField does not handle its own input but uses an NSTextView called the field editor to accept input.

  2. You need to react to the Enter key yourself. Take a look at the key handling documentation. Here is an answer with an example.

  3. To get mouse events you can use NSTrackingArea. See the docs for Mouse Tracking.

  4. I do not have any input on this except that sometimes text drawing can look bold when really what is happening is that the text is being drawn multiple times without erasing the background.

于 2011-08-02T17:00:02.447 回答