Make NSFormatter validate NSTextFieldCell continuously
In Cocoa, I have an NSOutlineView where the cells are NSTextFieldCell. The cell displays values which are strings that are formatted according to ce开发者_如何学JAVArtain rules (such as floats or pairs of floats with a space in between). I have made a custom NSFormatter to validate the text, and this seems to work with no problem.
However, the cell (or the outline view, I'm unsure what is causing this) only seems to use the formatter at the moment my editing would end. If I type some alphabetic characters into the text field (which violates the formatting rules), these characters show up -- the only way I notice the formatter doing its job is that I'm now prevented from moving keyboard focus away from this cell. If I return the contents of the cell to a valid form, then I can move focus away.
I have set both the cell and the outline view to be "continuous".
It would be better if I was unable to enter text into the cell in the first place. Is it possible to make it like that, and if so, how?
Answering my own question because I found the solution. There is an optional method to override on NSFormatter
, and this solves the problem. The optional method is:
- (BOOL) isPartialStringValid: (NSString*) partialString
newEditingString: (NSString**) newString
errorDescription: (NSString**) error
Here one can simply return NO
if the partialString
is invalid. One can return a fixed string by reference in newString
if one wants.
There is another method which could also have been used, but it is more complex:
- (BOOL) isPartialStringValid: (NSString**) partialStringPtr
proposedSelectedRange: (NSRangePointer) proposedSelRangePtr
originalString: (NSString*) origString
originalSelectedRange: (NSRange) origSelRange
errorDescription: (NSString**) error
精彩评论