It is possible to continuously update the UILabel

2019-09-18 21:40发布

问题:

In my application i have one UILabel and UITextField. Initially UILabel text in nil.
As soon as user enter some text in UITextField my UILabel text also Update.

Let say When user enter A in UITextField my UILabel immediately show A, B in UITextField my UILabel show B and so on.

To achieve this behaviour i used the shouldChangeCharactersInRange function of UITextFieldDelegate. But it always behind one character. say UITextField text = qwerty my UIlabel text show qwert

Please help me so i can continuously update the UILabel text as user enter value in UITextField

here is my code

 func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    mylabel.text = textfield.text
   return true
}

回答1:

You can register your textField for value change event:

[textField addTarget: self action:@selector(textFieldDidChange) forControlEvents:UIControlEventEditingChanged];

and in textFieldDidChange function update your label:

- (void)textFieldDidChange
{
    label.text = textField.text;
}

The function shouldChangeCharactersInRange is needed more for taking desisions whether to allow upcoming change or not



回答2:

You can use following code to change the text:

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{ 
   myLabel.text = [textField.text stringByReplacingCharactersInRange:range withString:string]
   return YES;
}


回答3:

In Swift

Register your edit events

textfield.addTarget(self, action:"changeLabel", forControlEvents:UIControlEvents.EditingChanged)


func changeLabel(){
    myLabel.text=textfield.text
}


回答4:

you can use this code easy to understand :

 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
   NSString *str = [NSString stringWithFormat:@"%@%@",yourtextfield.text,string];
   NSLog(@"%@",str);
   return YES;
}