繁体   English   中英

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

[英]What is the purpose of the Custom Formatter on Interface builder?

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

在此输入图像描述

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

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

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

你能举一个使用界面构建器的例子吗?

谢谢。

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM