我想实现一个 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.
最后但并非最不重要的一点是,由于某种原因,每几个字母,一个字母似乎是粗体。我不知道为什么。
我会很感激任何帮助。谢谢