使用 swift 在 xcode 6 中自定义 NSValueTransformer

问题描述:

有没有人在 xcode 6 beta 中使用 swift 成功实现自定义 NSValueTransformer?

Did anyone successfully implement a custom NSValueTransformer in xcode 6 beta with swift?

我有以下 swift 类:

I have the following swift class:

import Foundation

class myTransformer: NSValueTransformer {

  let amount = 100

  override class func transformedValueClass() -> AnyClass!
  {
    return NSNumber.self
  }

  override func transformedValue(value: AnyObject!) -> AnyObject! {
    return value.integerValue + amount
  }
}

所以这个转换器应该做的就是将 100 添加到 gui 中的给定值.

So all this transformer should do is, adding 100 to a given value in the gui.

如您所见,转换器类现在出现在 IB 的 Value Transformer 下拉列表中.

As you can see, the transformer class appears now in the Value Transformer drop down in IB.

但是如果我选择这个转换器,应用程序就会崩溃:

But if I choose this transformer the application crashes with:

2014-08-27 20:12:17.686 cdTest[44134:303] 
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', 
reason: 'Cannot find value transformer with name newTransformer'

在 AppDelegate 中注册这个转换器是否正确

Is it right to register this transformer in the AppDelegate with

override class func initialize() {
  let newTransformer = myTransformer()
}

有人知道这一切应该如何运作吗?

Does anyone know how this whole stuff should work?

亲切的问候!马丁

在您初始化 newTransformer 之后,您还应该包括以下行:

After you initialise newTransformer you should also include the line:

NSValueTransformer.setValueTransformer(newTransformer, forName: "myTransformer")

然后在您的 Interface Builder 中,您应该在 Value Transformer 下拉菜单下使用 myTransformer 而不是 newTransformer.

Then in your Interface Builder you should use myTransformer instead of newTransformer under the Value Transformer dropdown.