强制 cocoa 绑定在验证后更新 (swift)



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

我绑定了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)
}

最新更新