controlTextDidChange vs NSNumberFormatter
controlTextDidChange vs NSNumberFormatter
- Subject: controlTextDidChange vs NSNumberFormatter
- From: "Matt Gough" <email@hidden>
- Date: Tue, 14 Nov 2006 11:11:47 +0000
I have two NSTextFields (width and height) that I am trying to set up
so that whatever values are entered in either field that the width is
always half the height.
I have the following in my window controller's delegate:
- (void)controlTextDidChange:(NSNotification*)notification
{
NSTextField* field = [notification object];
BOOL widthChanged = field == widthField;
float fieldValue = [field floatValue];
if (widthChanged)
[heightField setFloatValue:fieldValue * 2.0];
else
[widthField setFloatValue:fieldValue / 2.0];
}
Without using any NSNumberFormatters on the fields this works as
expected for any sensible numeric values (including those that contain
decimal points)
However if I set up number formatter on the fields in my awakeFromNib
as follows:
NSNumberFormatter* formatter = [[[NSNumberFormatter alloc] init] autorelease];
[formatter setFormat:@"0.##"];
[widthField setFormatter:formatter];
[heightField setFormatter:formatter];
then a very odd thing happens:
E.g if widthField contains "10" (without the quotes)
then attempting to add a decimal point at the end causes widthField to
stay at "10". So if I was actually trying to get to "10.5" I would end
up with "105". However if there is already a decimal point in the
field (e.g "10.5") then it is happy for me to select the "5" and
replace it with a "6", but if I delete the "5" and then press "6" I
end up with "106".
After some experimentaion it seems that the call to :
float fieldValue = [field floatValue];
results in the number formatter kicking in and removing the
'redundant' decimal point at the end of the field. I was hoping that I
could maybe bracket my the above as follows:
NSString* oldString = [field stringValue];
float fieldValue = [field floatValue];
[field setStringValue:oldString];
but to no avail as even calling stringValue results in the decimal
point being removed.
It seems to me that this is something that other people must have done
correctly and that my code isn't unintentionally stupid.
Thanks for any help
Matt Gough
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden