How to capture user input in real time in NSTextField?

☆樱花仙子☆ 提交于 2019-12-09 19:36:30

问题


I can capture string when user click the button. and I also use the following method

- (BOOL)control:(NSControl *)control textShouldBeginEditing:(NSText *)fieldEditor

which declared in NSControlTextEditingDelegate Protocol. And when user begin editing, the button will be available.

My Question is: How to make the button disable when user delete all text (make the textField empty without clicking button)?

The above method seems can not do it...


回答1:


Look at using the NSControlTextDidChangeNotification or controlTextDidChange: delegate method (from NSControl) which is posted by the text field. When you receive the callback you can examine the text currently in the field to decide what to do.




回答2:


If your NSText is a NSTextView you may also use NSTextDelegate Protocol and NSTextViewDelegate Protocol.

Among others, the NSTextDelegate Protocol declares this delegate method:

textDidChange:

Informs the delegate that the text object has changed its characters or formatting attributes.

- (void)textDidChange:(NSNotification *)aNotification

Discussion

The name of aNotification is NSTextDidChangeNotification.

The NSTextDidChangeNotification is documented here NSTextDidChangeNotification




回答3:


Many ways to do the same thing. This version lets you easily catch specific keystrokes of interest.

- (BOOL)textView:(NSTextView *)aTextView shouldChangeTextInRange:(NSRange)affectedCharRange replacementString:(NSString *)replacementString{
     NSLog(@"last character entered: %@",replacementString);
}

for instance, if you were looking for the return key, you might then implement:

if ([replacementString characterAtIndex:0] == NSNewlineCharacter)
    NSLog(@"return pressed");


来源:https://stackoverflow.com/questions/19384185/how-to-capture-user-input-in-real-time-in-nstextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!