【问题标题】:macOS - Trying to use a custom NSFormatter on a NSTextField fails miserablymacOS - 尝试在 NSTextField 上使用自定义 NSFormatter 失败了
【发布时间】:2019-12-20 10:55:52
【问题描述】:

我正在尝试将NSFormatter 对象添加到NSTextField,因此我可以验证文本字段是否仅包含字母数字字符串。

所以我这样做:

  1. 我创建了一个新的Swift macOS 应用程序。
  2. 我将NSTextField 添加到视图控制器
  3. 我向视图控制器添加了一个自定义 Formatter
  4. 我使用界面构建器将文本字段的格式化程序出口连接到格式化程序对象。

我创建这个类并分配给 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 对象。我需要创建 Objective-CNSFormatter 子类。

说,当我运行项目时,文本字段消失了,我收到了这条消息,不管这意味着什么:

Failure1[3071:136161] 无法在 (NSWindow) 上设置 (contentViewController) 用户定义的检查属性:*** -stringForObjectValue:仅为抽象类定义。定义 -[FormatterTextNumbers stringForObjectValue:]!

我删除了文本字段和 Formatter 对象之间的连接,应用程序运行正常。

【问题讨论】:

    标签: objective-c swift cocoa nstextfield nsformatter


    【解决方案1】:

    你必须定义那个方法

    来自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;
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多