2

界面生成器具有可以拖动到文本字段的自定义格式化程序。

在此处输入图像描述

但是这个东西根本没有任何属性,而且像 Apple 那样典型的文档是不存在的。

我需要创建一个格式化程序,它可以接受数字、字母数字集中的文本和下划线并拒绝其他所有内容。

我怀疑这个自定义格式化程序是我需要的,但我该如何使用它?或者是否可以使用界面生成器上存在的常规格式化程序来做我需要的事情?

你能举一个使用界面生成器的例子吗?

谢谢。

4

2 回答 2

2

NSFormatter 类是一个抽象类,所以你需要继承它。为此,您需要实现以下方法。

- (BOOL)isPartialStringValid:(NSString *)partialString newEditingString:(NSString **)newString errorDescription:(NSString **)error;
- (NSString *)stringForObjectValue:(id)obj;
- (BOOL)getObjectValue:(out id *)obj forString:(NSString *)string errorDescription:(out NSString **)error;

创建一个子类,如:

。H

@interface MyFormatter : NSFormatter

@end

.m

@implementation MyFormatter

- (BOOL)isPartialStringValid:(NSString *)partialString newEditingString:(NSString **)newString errorDescription:(NSString **)error
{
    // In this method you need to write the validation
    // Here I'm checking whether the first character entered in the textfield is 'a' if yes, It's invalid in my case.
    if ([partialString isEqualToString:@"a"])
    {
        NSLog(@"not valid");
        return false;
    }
    return YES;
}

- (NSString *)stringForObjectValue:(id)obj
{
    // Here you return the initial value for the object
    return @"Midhun";
}

- (BOOL)getObjectValue:(out id *)obj forString:(NSString *)string errorDescription:(out NSString **)error
{
    // In this method we can parse the string and pass it's value (Currently all built in formatters won't support so they just return NO, so we are doing the same here. If you are interested to do any parsing on the string you can do that here and pass YES after a successful parsing
    // You can read More on that here: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSFormatter_Class/index.html#//apple_ref/occ/instm/NSFormatter/getObjectValue:forString:errorDescription:
    return NO;
}
@end
于 2015-03-15T10:11:51.380 回答
1

该对象对 OS X 非常有用。在 OS X 上,您可以将格式化程序附加到控件/单元格。在 iOS 中,我想您可以将格式化程序添加到 NIB 或情节提要,并将插座连接到它,但与以编程方式创建它相比,这并没有太大优势。

特别是,通用自定义格式化程序适用于当您想要添加自定义子类的实例时NSFormatter。您将自定义格式化程序拖到相关控件/单元格中,然后在身份检查器中设置其类。

如果该对象在对象库中不可用,您只能拖入特定格式化程序类的实例(例如NSNumberFormatter)。您将能够设置结果实例的类,但只能设置为该特定格式化程序类的子类。

如果您需要学习如何编写自定义格式化程序类,请参阅类参考NSFormatter数据格式化指南

于 2015-03-15T10:10:23.130 回答