ios - 界面构建器上的自定义格式化程序的用途是什么?

标签 ios iphone cocoa interface-builder nsformatter

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

enter image description here

但是这个东西根本没有属性,并且像 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

关于ios - 界面构建器上的自定义格式化程序的用途是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29059270/

相关文章:

ios - 在 ios 中的 sqlite 更新中出现错误

ios - 引用 Prefix.pch 中已安装的 pod

iphone - 刷新过程应在后台运行,但是子处理需要同步

ios - 是否有一个框架可以让开发 Mac 应用程序感觉更像开发 iOS 应用程序?

ios - 如何在 ViewController 之间传递委托(delegate)

ios - Apple Mach-O 链接器错误,我不知道为什么

iPhone AppStore 版本 : Code signing problem

iphone - iOS 开发 : How can I shorten a URL from my code?

objective-c - 分层 Cocoa WebView - 在顶部绘图?

python - 如何使用python在Xcode中读取.dcm?