如何在iPhone应用程序中自动调用UITextField的textDidChange方法

时间:2013-05-22 06:30:48

标签: iphone ios uitextfield

我在iphone应用程序中工作,其中有文本字段,我希望当任何文本更改时,以下方法应自动调用。

   -(void)textFieldTextDidChangeOneCI:(UITextField*)tf{



NSLog(@"Testing Successful Value %.2f",appDelegate.p_ClinInf_Yes_V_InModel);
appDelegate.p_ClinInf_Yes_NV_InModel  = [[textFieldOne text] floatValue];

appDelegate.p_ClinInf_No_NV_InModel=100-appDelegate.p_ClinInf_Yes_NV_InModel;

textFieldTwo.text=[NSString stringWithFormat:@"%.2f",appDelegate.p_ClinInf_No_NV_InModel];


NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];
NSString*string=textFieldOne.text;
if ([string rangeOfCharacterFromSet:set].location != NSNotFound) {
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"Only a number can be entered into this input field " delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    [alert release];
    textFieldOne.text=@"";


}

NSLog(@"Testing Successful CI Data  %.2f",appDelegate.p_ClinInf_Yes_NV_InModel);

}

目前我正在调用此

使用

    [textFieldOne addTarget:self action:@selector(textFieldTextDidChangeOneCI:) forControlEvents:UIControlEventEditingChanged];

4 个答案:

答案 0 :(得分:4)

试试这个

 - (void)viewDidLoad
{
[super viewDidLoad];

 [[NSNotificationCenter defaultCenter]
 addObserver:self
 selector:@selector(textFieldTextDidChangeOneCI:)
 name:UITextFieldTextDidChangeNotification
 object:textfield];
 }

同时修改你的方法

 -(void)textFieldTextDidChangeOneCI:(NSNotification *)notification
 {
UITextField *textfield=[notification object];
NSLog(@"%@",textfield.text);

 }

答案 1 :(得分:0)

尝试使用此

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
   [self textFieldTextDidChangeOneCI:textField];
    return YES;
}

答案 2 :(得分:0)

你可以这样做

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange:) name:UITextFieldTextDidChangeNotification object:nil];

让我知道它是否有效

答案 3 :(得分:0)

您可以为UITextFieldTextDidChangeNotification添加观察者,只要文本字段在文本字段中发生变化,就会发布该观察者。

请参阅以下代码:

// For textField1
[[NSNotificationCenter defaultCenter] 
addObserver:self 
   selector:@selector(anyMethod:)
       name:UITextFieldTextDidChangeNotification 
     object:textField1];

// For textField2
[[NSNotificationCenter defaultCenter] 
addObserver:self 
   selector:@selector(anyMethod:)
       name:UITextFieldTextDidChangeNotification 
     object:textField2];