Search code examples
swiftcocoanstextfield

Stop NSTokenField from trimming whitespace


I'm trying to set a stringValue to an NSTokenField (a subclass of NSTextField), but I've found that if the string starts with a space, it removes it. I want to keep the space. I tried applying a formatter with no luck as well. i.e.:

tokenField.stringValue = " 1"

This will actually readout "1" in the field.

Also, I want to format an integer but also keep zeros before it. i.e.:

    tokenField.stringValue = "001"

This will also readout "1" in the field.

I've tried overriding various functions with no luck. Any ideas?

Thanks!


Solution

  • From the documentation of NSTokenField:

    In OS X v10.4, NSTokenField trims whitespace around tokens but it does not trim whitespace in macOS versions 10.5.0 and 10.5.1. In OS X v10.5.2, you get whitespace-trimming behavior by either linking against the v10.4 binary or linking against the v10.5 binary and not implementing the tokenField(_:representedObjectForEditing:) method. If you do not want the whitespace-trimming behavior, link against the v10.5 binary and implement this method, returning the editing string if you have no represented object.

    Ok, it it a bit old and the name of the method isn't correct but it says:

    If you do not want the whitespace-trimming behavior, implement tokenField(_:representedObjectForEditingString:), returning the editing string if you have no represented object.