簡體   English   中英

macOS - 嘗試在 NSTextField 上使用自定義 NSFormatter 失敗了

[英]macOS - Trying to use a custom NSFormatter on a NSTextField fails miserably

我正在嘗試將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對象。 我需要創建一個NSFormatterObjective-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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM