I’m trying to make a simple Cocoa application where a number is input into a textfield. When a number is typed into one textfield the other textfield will automatically update with another number (and vice versa). The textfield that I’ve dragged into the window is the “Text Field with Number Formatter” from interface builder. I have the textfields set as delegate which allows them to automatically update. However, the formatting does not seem to work. I can’t input decimal numbers. Please help!!!
Header file here:
#import <Cocoa/Cocoa.h>
@interface AppDelegate : NSObject <NSApplicationDelegate> {
IBOutlet NSTextField *number1;
IBOutlet NSTextField *number2;
}
@property (assign) IBOutlet NSWindow *window;
@end
Implementation file here:
#import "AppDelegate.h"
@implementation AppDelegate
@synthesize window = _window;
-(void)controlTextDidChange:(NSNotification *) note {
NSTextField *changedField = [note object];
if (changedField == number1) {
float num1 = [number1 floatValue];
[number2 setFloatValue: (num1*2.0)];
}
if (changedField == number2) {
float num2 = [number2 floatValue];
[number1 setFloatValue: (num2/2.0)];
}
}
@end
This is a bit obscure, but what you are trying to do cannot really work but there is an alternative.
In your code you have:
The first line requests the current value of
number1. As you have a number formatter attached tonumber1it is called to format the text… and if you’ve entered, say,123.at this point the formatted result is123… and your decimal point is vanished. You’ll notice you cannot enter commas (thousands separators) either.So the fundamental problem is that after every character is typed your code is forcing it to be a valid number at that point.
The alternative is to only do your action when the user has entered a complete number. You can either write code yourself to analyze the input as each character is typed, or you can use the quick and easy method of waiting until the user hits and responding to the action.
To do the latter change your code to:
and connect it to the control as the “selector” and remove the “delegate” connection you already have.
This solution is less “dynamic” than what you tried, but it does work. To get the dynamic response back you’ll need to write more involved code as stated above.