简体   繁体   中英

how to multiply two float values and there result must be shows on button title

I have text bot i want that when i enter any value like 3 in that then it should mulitpy by 12 and display 36 on button title automatically when i enter any number in text field the title should change i am adding following code but it alwasy shows zero i am adding this code in viewdidLoad

     float monthText = [[monthTextField text] floatValue];
    float year=12;

float monthButtonTitle=monthText*year;


NSString *titleMonth = [NSString stringWithFormat:@"%d",monthButtonTitle];


[monthButton setTitle:titleMonth forState:UIControlStateNormal];
 [NSString stringWithFormat:@"%f",monthButtonTitle];

implement the UITextFieldDelegate

yourTextField.delegate = self // self maybe the controller;

then in method

- (void)textFieldDidEndEditing:(UITextField *)textField

get the new value you enter

float v = [textField.text floatValue];

calc it, , update the label

and if your only allow to input numeric , you can do this

textField.keyboardType = UIKeyboardTypeNumberPad;

#define NUMBERSPERIOD @"0123456789."

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
 NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERSPERIOD] invertedSet];
 NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
 BOOL basicTest = [string isEqualToString:filtered];
 // Add any predicate testing here
 return basicTest;
}
 NSString *titleMonth =  [NSString stringWithFormat:@"%f",monthButtonTitle];

[monthButton setTitle:titleMonth forState:UIControlStateNormal];

Add action to your textfield like this

[yourTextField addTarget:self action:@selector(textFieldTextDidChange:) forControlEvents:UIControlEventEditingChanged];

Then implement method textFieldTextDidChange: like this

- (void) textFieldTextDidChange:(UITextField *)tf {
    float monthText = [[tf text] floatValue];
    float year=12;
    float monthButtonTitle=monthText*year;
    NSString *titleMonth = [NSString stringWithFormat:@"%d",monthButtonTitle];
    [monthButton setTitle:titleMonth forState:UIControlStateNormal];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM