2011-03-05 42 views
14

我對Mac開發很新穎(來自web和iOS背景),我無法弄清楚每當NSTextView的值發生變化時我如何獲得通知。有任何想法嗎?NSTextView的值改變了

回答

35

Ups我剛剛看到你想要從NSTextView回調,而不是NSTextField

只需添加對象的頭部,該對象應該是協議的代表

@interface delegateAppDelegate : NSObject <NSApplicationDelegate, NSTextViewDelegate> { 
    NSWindow *window; 
} 

之後,你添加像

-(void)textDidChange:(NSNotification *)notification { 
    NSLog(@"Ok"); 
} 

的方法確保您連接應接受委託

+0

就是這樣!我很確定這是我嘗試過的事情之一,但顯然不太對。它的工作現在:-)謝謝! – tarnfeld 2011-03-05 11:56:42

+2

NSTextViewDelegate實現NSTextDelegate這是什麼工作,但你也可以使用特定的NSTextViewDelegate方法,如 - (布爾)textView:(NSTextView *)aTextView shouldChangeTextInRange:(NSRange)affectedCharRange replacementString:(NSString *)replacementString – valexa 2012-04-24 10:53:40

+5

這將只會從用戶直接與NSTextView交互(例如,用戶在文本框中輸入或複製並粘貼到剪貼板中或從中剪切)。如果以編程方式更改textView,它將不會捕獲對textView的更改,如同在'textView.string = @「Foo」;'中一樣。爲此,您需要成爲textview的textStorage的委託,就像在'textView.textStorage.delegate = self;'中一樣,並且在自己的對象的類上實現' - (void)textStorageWillProcessEditing:(NSNotification *)aNotification'。這個井可以同時獲得用戶驅動的更改和直接的屬性設置器更改。 – Joel 2015-01-07 02:07:06

-1

設置nstextfield的委託。在您添加代理協議 在.m文件委託的.h文件添加一個方法類似-(void)controlTextDidChange:(NSNotification *)obj { NSLog(@"ok"); }

我希望幫助

+1

這是爲NSTextField而不是NSTextView – valexa 2012-04-24 11:01:13

+0

NSTextView是NSTextField的一個子類,所以它的代表 – kezi 2013-03-16 01:33:28

+3

我很害怕https://developer.apple.com/library/mac/documentation/cocoa/reference/applicationkit/classes/NSTextView_Class/Reference/Reference.html清楚地顯示NSTextView繼承自NSText從NSView繼承。 NSTextField繼承自也繼承自NSView的NSControl。 controlTextDidChange是NSControl的委託方法,這意味着NSTextField可以訪問controlTextDidChange,但NSTextView不會因爲它不從NSControl或NSTextField繼承。 – 2014-02-28 17:34:16

-2

設置委託,然後使用

- (void) controlTextDidChange: (NSNotification *) notification 
{ 
} 
+1

這是爲NSTextField而不是NSTextView – valexa 2012-04-24 11:00:36

+0

NSTextView是NSTextField的子類,所以它的代表 – kezi 2013-03-16 01:33:05

+6

@kdogisthebest NSTextView不是NSTextField的子類。 – 2013-03-18 07:10:04

2

這裏NSTextView(不NSScrollView)與對象的委託財產的解決方案:

NSTextView *textView = ...; 

@interface MyClass : NSObject<NSTextStorageDelegate> 
@property NSTextView *textView; 
@end 

MyClass *myClass = [[MyClass alloc] init]; 
myClass.textView = textView; 
textView.textStorage.delegate = myClass; 

@implementation MyClass 
- (void)textStorageDidProcessEditing:(NSNotification *)aNotification 
{ 
    // self.textView.string will be the current value of the NSTextView 
    // and this will get invoked whenever the textView's value changes, 
    // BOTH from user changes (like typing) or programmatic changes, 
    // like textView.string = @"Foo"; 
} 
@end