我正在尝试将NSFormatter
对象添加到NSTextField
,因此我可以验证文本字段是否仅携带字母数字字符串。
所以我这样做:
- 我创建了一个新的
Swift
macOS 应用程序。 - 我向视图控制器添加
NSTextField
- 我向视图控制器添加了自定义
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
子类。
说,当我运行项目时,文本字段消失,我收到以下消息,无论这意味着什么:
失败1[3071:136161] 无法在 (NSWindow( 上设置(内容视图控制器(用户定义的检查属性:*** -stringForObjectValue:仅为抽象类定义。 定义 -[FormatterTextNumbers stringForObjectValue:]!
我删除了文本字段和格式化程序对象之间的连接,应用程序运行良好。
你必须定义那个方法
来自 AppleNSFormatter
文档(实际上是半抽象的(
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;