swift - 验证后强制 cocoa 绑定(bind)更新(快速)

标签 swift macos cocoa-bindings nstextfield

我在 controlTextDidEndEditing 中检查并删除 NSTextField 中的空格,但这些更改未反射(reflect)在 cocoa 绑定(bind)中(CoreData 条目未更新)。 NSTextField 已更新,但如果您单击条目外并返回到空格中,则会返回。 如何触发绑定(bind)对象更新数据存储?

我绑定(bind)了 NSTextField 的 .value,我什至尝试在更新后将 .objectValue 设置为 .stringValue,但它不起作用。

override func controlTextDidEndEditing(obj: NSNotification) {
    Swift.print("editing is done now")

    let textField:NSTextField = obj.object as! NSTextField

    //if last character is a space remove it.
    while textField.stringValue.characters.last == " "
    {
        Swift.print("last char is a space")
        textField.stringValue.removeAtIndex(textField.stringValue.endIndex.predecessor())

    }

    //save to database now.
    let dele:AppDelegate = NSApplication.sharedApplication().delegate as! AppDelegate
    dele.saveAction(nil)

}

最佳答案

textField.stringValue 不是引用类型。您可以将该值分配回文本字段。

有更方便的修剪字符串的方法

override func controlTextDidEndEditing(obj: NSNotification) {
  Swift.print("editing is done now")

  let textField = obj.object as! NSTextField
  let string = textField.stringValue
  textField.stringValue = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

  //save to database now.
  let dele:AppDelegate = NSApplication.sharedApplication().delegate as! AppDelegate
  dele.saveAction(nil)
}

关于swift - 验证后强制 cocoa 绑定(bind)更新(快速),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35685715/

相关文章:

swift - 呈现带有标签栏的 View Controller

arrays - 如何将不同类型的值转换为数据字节

objective-c - XCode dylib 在/usr/lib 中查找

cocoa - 手动 Cocoa 绑定(bind)不改变观察到的 KeyPath

objective-c - 使用 Cocoa Bindings,以编程方式更改 NSTextField 的值不会更新模型

ios - Realm - 我可以在删除对象后保存对象吗?

swift - 使用 Objective-C 选择器声明方法时出错

macos - Mac OS X 上的配置文件 GLSL 片段着色器?

macos - 使用 NSArrayController 过滤单列 NSTableView

swift - 字符串无法转换为字符串 :AnyObject