NSTextView值已更改

tar*_*eld 15 events callback nstextview

我对mac开发很新(来自网络和iOS背景)我无法弄清楚每次NSTextView的值发生变化时我都能得到通知.有任何想法吗?

lbr*_*dnr 38

我刚刚看到你想从NSTextView而不是NSTextField回调

只需添加对象的标题,该标题应该是委托协议

@interface delegateAppDelegate : NSObject <NSApplicationDelegate, NSTextViewDelegate> {
    NSWindow *window;
}
Run Code Online (Sandbox Code Playgroud)

之后你添加一个像这样的方法

-(void)textDidChange:(NSNotification *)notification {
    NSLog(@"Ok");
}
Run Code Online (Sandbox Code Playgroud)

确保已将NSTextView(而非NSScrollView)的委托属性与应接收委托的对象相关联

  • 这只会从用户直接与NSTextView交互中获得更改(例如,用户在textview中键入或复制并粘贴到其中或从中剪切).如果以编程方式更改textView,它将不会捕获对textView的更改,如`textView.string = @"Foo";`.为此,您需要成为textview的textStorage的委托,如`textView.textStorage.delegate = self;`并在self的对象的类上实现` - (void)textStorageWillProcessEditing:(NSNotification*)aNotification`.这很好地得到了用户驱动的更改和直接的属性设置器更改. (7认同)
  • NSTextViewDelegate实现了NSTextDelegate,它可以使用特定的NSTextViewDelegate方法,如 - (BOOL)textView:(NSTextView*)aTextView shouldChangeTextInRange:(NSRange)affectedCharRange replacementString:(NSString*)replacementString (2认同)

Joe*_*oel 5

这是解决方案:

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
Run Code Online (Sandbox Code Playgroud)