Question

I am trying to build an app that manage some decimal values (as practice as I am beginner) in some textFields. I want the app to launch with those numbers being 0.00 (no currency, just numbers). I do not know if I have to handle that inside an overridden "init" method.

Also, is it possible to handle those same textFields to go back to 0.00 if the user delete is current number and just leaves it empty. Thank you!

Was it helpful?

Solution

1) Inside viewDidAppear, you'll want to set the text of the UITextFields --

[self textFieldName] setText:@"0.00"];

2) Your controller should adhere to UITextFieldDelegate and it should I would implement it something like the following --

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string  
{
    NSCharacterSet *characterSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:characterSet] componentsJoinedByString:@""];
    return [string isEqualToString:filtered];
}

3) To reset the text field, I would implement the UITextFieldDelegate method as follows --

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if ([[textField text] isEqualToString:@""]) {
        [textField setText:@"0.00"];
    }
}

Post a comment if you have a further questions. Good luck.

OTHER TIPS

There are perhaps multiple ways to do this. A straightforward way is to set the textField value to zero in a viewDidLoad. Let's assume that you have nib file and have already connected your UITextField to the outlet in the nib.

So you have something like:

@property (nonatomic) IBOutlet UITextField *textField;

And then in viewDidLoad

- (void)viewDidLoad
{
    self.textField.text = @"0.00";
}

For when the user deletes the value you need to make your viewController the delegate for the UITextField and then implement the textFieldDidEndEditing method.

- (void)textFieldDidEndEditing:(UITextField *)textField
{
   // Check to see if the value is empty
   if ([self.textField.text isEqualToString:@""])
   {
       self.textField.text = @"0.00";
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top