![](/img/trans.png)
[英]Accessing `stringValue` of a NSTextField with custom NSFormatter, in `controlTextDidChange` method makes it non-editable.
[英]macOS - Trying to use a custom NSFormatter on a NSTextField fails miserably
我正在嘗試將NSFormatter
對象添加到NSTextField
,因此我可以驗證文本字段是否僅包含字母數字字符串。
所以我這樣做:
Swift
macOS 應用程序。NSTextField
Formatter
添加到視圖控制器我創建這個類並分配給 Formatter 對象。
FormatterTextNumbers.h
#import <Foundation/Foundation.h>
@import AppKit;
NS_ASSUME_NONNULL_BEGIN
@interface FormatterTextNumbers : NSFormatter
@end
NS_ASSUME_NONNULL_END
FormatterTextNumbers.m
#import "FormatterTextNumbers.h"
@implementation FormatterTextNumbers
- (BOOL)isAlphaNumeric:(NSString *)partialString
{
static NSCharacterSet *nonAlphanumeric = nil;
if (nonAlphanumeric == nil) {
nonAlphanumeric = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'. -"];
nonAlphanumeric = [nonAlphanumeric invertedSet];
}
NSRange range = [partialString rangeOfCharacterFromSet:nonAlphanumeric];
if (range.location != NSNotFound) {
return NO;
} else {
return YES;
}
}
- (BOOL)isPartialStringValid:(NSString *)partialString
newEditingString:(NSString * _Nullable __autoreleasing *)newString
errorDescription:(NSString * _Nullable __autoreleasing *)error {
if ([partialString length] == 0) {
return YES; // The empty string is okay (the user might just be deleting everything and starting over)
} else if ([self isAlphaNumeric:partialString]) {
*newString = partialString;
return YES;
}
NSBeep();
return NO;
}
你會問,如果我的項目使用Swift
,為什么我在Objective-C
有這些類? 簡單:如果我使用Swift
創建Formatter
類的子類, Xcode
不會讓我將該子類分配給Formatter
對象。 我需要創建一個NSFormatter
的Objective-C
子類。
說,當我運行項目時,文本字段消失,我收到這條消息,無論這意味着什么:
Failure1[3071:136161] 無法在(NSWindow)上設置(contentViewController)用戶定義的檢查屬性:*** -stringForObjectValue:僅為抽象類定義。 定義 -[FormatterTextNumbers stringForObjectValue:]!
我刪除了文本字段和 Formatter 對象之間的連接,應用程序運行良好。
你必須定義那個方法
來自NSFormatter
Apple 文檔(實際上是半抽象的)
Summary The default implementation of this method raises an exception. Declaration - (NSString *)stringForObjectValue:(id)obj;
其實同樣是為了
- (BOOL)getObjectValue:(out id _Nullable * _Nullable)obj forString:(NSString *)string errorDescription:(out NSString * _Nullable * _Nullable)error;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.