【发布时间】:2011-07-09 07:50:46
【问题描述】:
我对 mac 开发非常陌生(来自 web 和 iOS 背景),我无法弄清楚每次 NSTextView 的值发生变化时如何获得通知。有什么想法吗?
【问题讨论】:
标签: events callback nstextview
我对 mac 开发非常陌生(来自 web 和 iOS 背景),我无法弄清楚每次 NSTextView 的值发生变化时如何获得通知。有什么想法吗?
【问题讨论】:
标签: events callback nstextview
我刚刚看到你想要来自 NSTextView 而不是 NSTextField 的回调
只需添加应该是协议委托的对象的标头
@interface delegateAppDelegate : NSObject <NSApplicationDelegate, NSTextViewDelegate> {
NSWindow *window;
}
然后你添加一个类似的方法
-(void)textDidChange:(NSNotification *)notification {
NSLog(@"Ok");
}
确保将 NSTextView(不是 NSScrollView)的委托属性与应接收委托的对象连接
【讨论】:
textView.string = @"Foo"; 那样以编程方式更改 textView,它不会捕获对 textView 的更改。为此,您需要成为 textview 的 textStorage 的代表,如 textView.textStorage.delegate = self; 并在 self 对象的类上实现 - (void)textStorageWillProcessEditing:(NSNotification *)aNotification。这很好地获得了用户驱动的更改和直接的属性设置器更改。
解决办法如下:
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
【讨论】:
设置 nstextfield 的委托。在委托的 .h 文件中添加委托协议
在 .m 文件中添加类似 -(void)controlTextDidChange:(NSNotification *)obj {
NSLog(@"ok");
}
希望对你有帮助
【讨论】:
设置委托,然后使用
- (void) controlTextDidChange: (NSNotification *) notification
{
}
【讨论】: