“接口”构建器上的“自定义格式化程序”的用途是什么?

时间:2015-03-15 09:49:45

标签: ios iphone cocoa interface-builder nsformatter

“界面”构建器具有此自定义格式化程序,可以将其拖动到文本字段。

enter image description here

但是这个东西根本没有属性,而Apple的典型文档也不存在。

我需要创建一个格式化程序,而不是接受数字,来自字母数字集和下划线的文本,并拒绝其他所有内容。

我怀疑这个自定义格式化程序是我需要的,但我该如何使用它?或者可以使用接口构建器上存在的常规格式化器来完成我需要的工作吗?

您能举例说明使用界面构建器吗?

感谢。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

该对象主要用于OS X.在OS X上,您可以将格式化程序附加到控件/单元格。在iOS中,我认为您可以将格式化程序添加到NIB或故事板并将其连接到它,但是以编程方式创建它并没有多大优势。

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

如果对象库中没有该对象,则只能拖动特定格式化程序类的实例(例如NSNumberFormatter)。您可以设置结果实例的类,但只能设置该特定格式化程序类的子类。

如果您需要了解如何编写自定义格式化程序类,请参阅NSFormatterData Formatting Guide的类参考。