1

我有文本机器人,我希望当我在其中输入任何值(如 3)时,它应该乘以 12,并在按钮标题上自动显示 36,当我在文本字段中输入任何数字时,标题应该更改我正在添加以下代码,但它总是显示零我在 viewdidLoad 中添加此代码

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

float monthButtonTitle=monthText*year;


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


[monthButton setTitle:titleMonth forState:UIControlStateNormal];
4

3 回答 3

1
 [NSString stringWithFormat:@"%f",monthButtonTitle];

实现UITextFieldDelegate

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

然后在方法中

- (void)textFieldDidEndEditing:(UITextField *)textField

获取您输入的新值

float v = [textField.text floatValue];

计算它,更新标签

如果你只允许输入数字,你可以这样做

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;
}
于 2012-05-09T06:38:55.167 回答
0
 NSString *titleMonth =  [NSString stringWithFormat:@"%f",monthButtonTitle];

[monthButton setTitle:titleMonth forState:UIControlStateNormal];
于 2012-05-09T06:39:33.083 回答
0

像这样向您的文本字段添加操作

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

然后实现方法 textFieldTextDidChange: 像这样

- (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];
}
于 2012-05-09T06:51:59.443 回答