All,
Is there a way to impose character limit on a textfield? I would like to limit a textfield input to 30 characters.
I can achieve this programmatically, but wanted to know if it’s achievable through Object Library (Like Number Formatter for e.g.)
Best way is using a subclass of NSFormatter and implement the isPartialStringValid method. The partialString (first) argument is the new string. If it length of the new string exceeds the maximum field length return false and the character will not be inserted into the text field; otherwise return true.
How do I use the NSFormatter Class? Do I just drag this from the Object Library onto the Text Field Cell? How do I call the isPartialStringValid of this class?
The is a method of NSString which returns the length as a NSUInteger. You could write a “LimitedEntryFormatter” (a subclass of NSFormatter) with the method pointed by DJ, so:
Choose “New > File.”, then Objective-C class, give the name “LimitedEntryFormatter”, make it a subclass of NSFormatter, paste this code into the .m file, and in IB, drag a NSFormatter to your text field, set its class to your new class, and try to enter text.
To set the formatter in AppleScriptObjC for 2 fields , each having different character limits:
on applicationWillFinishLaunching_(aNotification)
set Field1Formatter to current application's class "LengthFormatter"'s alloc()'s init()
Field1Formatter's setMaxLength_(5)
Field1's |cell|()'s setFormatter_(Field1Formatter)
set Field2Formatter to current application's class "LengthFormatter"'s alloc()'s init()
Field2Formatter's setMaxLength_(10)
Field2's |cell|()'s setFormatter_(Field2Formatter)
end applicationWillFinishLaunching_
The only issue currently is that after typing in field1/field2 and then going to a different field, the typed text disappears. Any idea why this is happening? Did I miss something?
Correct shane… I don’t know why I missed that and also my test projects (for this topic) works like a charm. But nevertheless it should always be in there, even if if you don’t make any coercions.