2011-04-07 79 views
14

如何将事件附加到NSTextField,以便单击它时?那里有没有例子?将单击操作添加到NSTextField

+0

当用户点击文本字段或当用户输入文本字段时(例如通过点击它或键入Tab)? – 2011-04-08 09:41:40

+0

当用户点击文本字段时。 – AdamB 2011-04-08 18:14:36

+0

看看http://stackoverflow.com/questions/684166/which-delegate-method-i-should-use-to-respond-to-clicks-on-a-nstextfield – Ryan 2012-01-01 07:36:45

回答

0

你正在寻找的方法是 - textShouldBeginEditing:

你要设置的NSTextField的代表,首先。

+1

有什么我可以看的例子吗? – AdamB 2011-04-08 00:12:27

+23

'-control:textShouldBeginEditing:'当用户单击文本字段时不发送。它在用户开始在文本字段中输入文本时发送。 – 2011-04-08 09:51:37

7

你可以试试这个:它适用于我。

@interface customTextField : NSTextField 
    @property (strong) id target; 
    @end 

    @implementation customTextField 

    - (void)mouseDown:(NSEvent *)theEvent 
    { 
     [self sendAction:@selector(clickAction:) to:[self target]]; 
    } 

    @end 

谢谢。

+0

最好使用目标的动作。你可以通过CTRL +拖动设置它来源代码的行动。 [self sendAction:self.action to:self.target]; – Borzh 2015-09-21 01:53:08

+2

你不应该复制他人的答案。它的原始来源是:http://stackoverflow.com/questions/9184555/click-on-nstextfield-label-to-emulate-hyperlink-to-a-folder – 2015-12-23 09:10:20

+0

我没有复制,它的巧合,该链接也给了同样的答案。 – 2016-04-08 13:24:35

3
NSClickGestureRecognizer *click = [[NSClickGestureRecognizer alloc] initWithTarget:self action:@selector(myTextFieldClicked:)]; 
[self.myTextField addGestureRecognizer:click]; 
+0

伟大的解决方案。不需要子类。 – adev 2017-11-11 00:32:54

+0

我真的很喜欢这个,但似乎不适用于无法选择或编辑的静态文本字段,真的好奇为什么!? – Hofi 2017-12-07 16:49:47