设置 NSTextView 的最大文本大小

Set the maximum text size for NSTextView

提问人:Igor 提问时间:11/11/2023 最后编辑:Igor 更新时间:11/21/2023 访问量:52

问:

SO 和 Google 上的所有帖子都指向了 NSTextField 的一种方法。我需要它来制作 NSTextView。

我正在开发跨平台应用程序,其中我需要一个 NSTextView,而不是一个 Field,其数据将进入大小限制为 255 个字符的 DB 字段。

因此,我宁愿阻止应用程序的用户输入超过 255 个字符,也不愿意外地剪切数据库插入的文本。

我知道该类没有内置任何内容,但也许有一种方法可以使其以某种方式工作。

TIA!!

编辑:

我尝试实现建议的方法,但失败了。

这是我所做的:

- (BOOL)textView:(NSTextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    [super shouldChangeTextInRange:range replacementText:text];
    // code to check the number of characters
}

我收到以下错误/警告:

warning: instance method '-shouldChangeTextInRange:replacementText:' not found
      (return type defaults to 'id') [-Wobjc-method-access]
    [super shouldChangeTextInRange:range replacementText:text];
           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/AppKit.framework/Headers/NSTextView.h:64:12: note: 
      receiver is instance of class declared here
@interface NSTextView : NSText <NSUserInterfaceValidations, NSTextInputClient, NSTextLayoutOrientationProvider, NSDraggingSource, NSText...
           ^
1 warning generated.

我做错了什么?

我确实在 NSTextView 中看到了该函数......

macOS 可可 NSTextView

评论

0赞 Willeke 11/11/2023
您是否尝试过实现委托方法?它类似于 uitextview 中的限制字符数textView(_:shouldChangeTextIn:replacementString:)
0赞 Igor 11/12/2023
@Willeke,谢谢指针。然而,根据 developer.apple.com/documentation/uikit/uitextviewdelegate/... 它从 10.13 开始可用。
0赞 Igor 11/12/2023
还有一个问题 - UITextView 和 NSTextView 之间有什么联系?
0赞 Willeke 11/12/2023
UITextView是 iOS,是 macOS。NSTextView
0赞 Willeke 11/12/2023
textView:shouldChangeTextInRange:replacementString: (NSTextViewDelegate) 从 Mac OS X 10.0 开始可用。 () 从 iOS 2.0 和 Mac Catalyst 13.0 开始可用。textView:shouldChangeTextInRange:replacementText:UITextViewDelegate

答:

0赞 Willeke 11/21/2023 #1

复制自 uitextview 中的限制字符数,并改编为 ,在文本视图的委托中实现:NSTextViewDelegate

- (BOOL)textView:(NSTextView *)textView shouldChangeTextInRange:(NSRange)affectedCharRange 
    replacementString:(NSString *)replacementString {
    return textView.string.length + (replacementString.length - affectedCharRange.length) <= 140;   
}

在子类中的相同技巧:NSTextView

- (BOOL)shouldChangeTextInRange:(NSRange)affectedCharRange 
    replacementString:(NSString *)replacementString {
    return [super shouldChangeTextInRange:affectedCharRange replacementString:replacementString] &&
        (self.string.length + (replacementString.length - affectedCharRange.length) <= 140);    
}

评论

0赞 Igor 11/21/2023
子类有效,但部分有效。它通过字符的键入字符处理 cse,并在字符总数较少时处理粘贴文本时的情况。但是我还想检查粘贴的文本,如果我不粘贴全文,则粘贴部分文本。假设我的限制为 20。我目前有 10 个字符,正在尝试粘贴 20 个字符。我希望粘贴前 10 个字符,删除后 10 个字符。
0赞 Willeke 11/21/2023
@Igor 这是一个新问题。
0赞 Igor 11/21/2023
做。请参见 stackoverflow.com/questions/77523943/...。感谢。
0赞 Igor 11/23/2023
我试图实现我想要的东西,但失败了。你能看看我对上述问题的编辑吗?感谢。