【问题标题】:NSTextView value changedNSTextView 值已更改
【发布时间】:2011-07-09 07:50:46
【问题描述】:

我对 mac 开发非常陌生(来自 web 和 iOS 背景),我无法弄清楚每次 NSTextView 的值发生变化时如何获得通知。有什么想法吗?

【问题讨论】:

    标签: events callback nstextview


    【解决方案1】:

    我刚刚看到你想要来自 NSTextView 而不是 NSTextField 的回调

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

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

    然后你添加一个类似的方法

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

    确保将 NSTextView(不是 NSScrollView)的委托属性与应接收委托的对象连接

    【讨论】:

    • 就是这样!我很确定这是我尝试过的事情之一,但显然做得不太对。它现在可以工作了 :-) 谢谢!
    • NSTextViewDelegate 实现了 NSTextDelegate 这就是可行的,但您也可以使用特定的 NSTextViewDelegate 方法,例如 - (BOOL)textView:(NSTextView *)aTextView shouldChangeTextInRange:(NSRange)affectedCharRange replacementString:(NSString *)replacementString跨度>
    • 这只会从直接与 NSTextView 交互的用户那里获得更改(例如,用户在 textview 中键入或复制并粘贴到其中或从中剪切)。如果您像textView.string = @"Foo"; 那样以编程方式更改 textView,它不会捕获对 textView 的更改。为此,您需要成为 textview 的 textStorage 的代表,如 textView.textStorage.delegate = self; 并在 self 对象的类上实现 - (void)textStorageWillProcessEditing:(NSNotification *)aNotification。这很好地获得了用户驱动的更改和直接的属性设置器更改。
    • 谢谢乔尔,找到此信息时遇到了麻烦。
    【解决方案2】:

    解决办法如下:

    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
    

    【讨论】:

      【解决方案3】:

      设置 nstextfield 的委托。在委托的 .h 文件中添加委托协议 在 .m 文件中添加类似 -(void)controlTextDidChange:(NSNotification *)obj { NSLog(@"ok"); }

      的方法

      希望对你有帮助

      【讨论】:

      • 这是为 NSTextField 而不是 NSTextView
      • NSTextView 是 NSTextField 的子类,它的代表也是如此
      • 恐怕developer.apple.com/library/mac/documentation/cocoa/reference/… 清楚地表明 NSTextView 继承自 NSText 继承自 NSView。 NSTextField 继承自 NSControl,NSControl 也继承自 NSView。 controlTextDidChange 是 NSControl 的委托方法,这意味着 NSTextField 可以访问 controlTextDidChange 但 NSTextView 不能,因为它不是从 NSControl 或 NSTextField 继承的。
      【解决方案4】:

      设置委托,然后使用

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

      【讨论】:

      • 这是为 NSTextField 而不是 NSTextView
      • NSTextView 是 NSTextField 的子类,它的代表也是如此
      • @kdogisthebest NSTextView 不是 NSTextField 的子类。
      猜你喜欢
      • 1970-01-01
      • 2014-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-06
      • 2013-01-16
      • 2011-05-17
      相关资源
      最近更新 更多