NumberFormatter


#1

Question: How to change the properties of the NumberFormatter? Or how to delete it once you have added it to the NSTextFieldCell? After adding the Formatter, I am not able to change it’s properties because I don’t know how to select it, I just don’t find it. I also do not know how I can delete the Formatter from the TextFieldCell. How is it done?


#2

If you keep clicking, eventually you will select the Text Field Cell. At this point you will need to use either the Jump Bar, or the expanded document outline (the expanded version of the IB dock), to select the number formatter, which appears below the cell in the hierarchy. You can remove it by deleting it from the hierarchy.

Adam


#3

Ah, thank you. And is it possible to tell the NumberFormatter the number of digits to present via IB (let’s say 2 digits after the separator)? Or is that just possible with coding?


#4

Yes. For example, you change the formatter Behavior to 10.4+ Custom, you can set Format (+) to: “#,###.##”.


#5

Sorry, me again. I do not really understand all fields in there… I still have some weird behavior. I thought, when the multiplier is set to 100, I should get a 45 when I type in a 0.45, but I don’t! And, what about the Format (±) fields? I set the format with the Fraction Digits fields! That worked! Another question: What if I have a number with 4 digits. I want to keep that accuracy in my data. But I just want to display 2 digits for clarity. First: Is the accuracy kept with that method? Second: When I type in the TableView to change a number, I want to see 4 digits again! Is that possible without coding?

Cheers
Phil


#6

I believe that you will keep the accuracy you need as long as the number formatter you use (for editing) preserves it.

What you want to do is use a different NSNumberFormatter when editing. Unfortunately this isn’t easy to do. The best way I could come up with to do it was to implement the delegate method tableView:willDisplayCell:forTableColumn:row:.

- (void)tableView:(NSTableView *)theTableView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row { if ([[tableColumn identifier] isEqualToString:@"expectedRaise"]) { NSNumberFormatter *f = [[NSNumberFormatter alloc] init]; if (row == [tableView editedRow] && [[tableView tableColumns] indexOfObject:tableColumn] == [tableView editedColumn]) { [f setNumberStyle:NSNumberFormatterSpellOutStyle]; } else { [f setNumberStyle:NSNumberFormatterPercentStyle]; } [cell setFormatter:f]; } }

Basically this method gives us an opportunity to modify the cell before it’s shown. In this case we assign a different number formatter to it. Note that this overwrites any number formatter setting we made in the XIB file. If you wanted to configure the number formatter in IB you could create them as independent objects in the XIB and add outlets to them.

Note that I’ve never done this in a production app so there may be pitfalls related to this approach.

Adam