我试图将NSFormatter对象添加到NSTextField中,以便验证textfield是否只运行字母数字字符串。
所以我就这么做:
Swift macOS应用程序。NSTextField --向视图控制器H 211H 112,我使用接口生成器将文本字段的格式化器出口连接到格式化程序对象。H 213G 214我创建这个类并分配给格式化程序对象。
FormatterTextNumbers.h
#import <Foundation/Foundation.h>
@import AppKit;
NS_ASSUME_NONNULL_BEGIN
@interface FormatterTextNumbers : NSFormatter
@end
NS_ASSUME_NONNULL_ENDFormatterTextNumbers.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;
}您会问,如果我的项目使用Objective-C,为什么在Swift中有这些类?简单:如果我使用Formatter创建Swift类的子类,Xcode将不允许我将该子类分配给Formatter对象。我需要创建一个NSFormatter的NSFormatter子类。
说,当我运行这个项目时,文本字段消失了,我得到了这条消息,不管这意味着什么:
Failure13071:136161未能在(NSWindow):*-stringForObjectValue上设置(contentViewController)用户定义的检查属性:仅为抽象类定义。定义-FormatterTextNumbers stringForObjectValue:!
我删除文本字段和格式化程序对象之间的连接,应用程序运行良好。
发布于 2019-12-20 11:07:50
你必须定义那个方法
NSFormatter的苹果文档(实际上是半抽象的)
摘要此方法的默认实现将引发异常。声明- (NSString *)stringForObjectValue:(id)obj;
其实也是一样的
- (BOOL)getObjectValue:(out id _Nullable * _Nullable)obj forString:(NSString *)string errorDescription:(out NSString * _Nullable * _Nullable)error;https://stackoverflow.com/questions/59424073
复制相似问题