Rizwan Shaikh
Rizwan Shaikh

Reputation: 2904

It is possible to continuously update the UILabel text as user enter value in UITextField in iOS

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
}

Upvotes: 0

Views: 1477

Answers (4)

Mukesh
Mukesh

Reputation: 3690

In Swift

Register your edit events

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


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

Upvotes: 2

Nitin
Nitin

Reputation: 451

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;
}

Upvotes: 1

nilam_mande
nilam_mande

Reputation: 931

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;
}

Upvotes: 2

Misha
Misha

Reputation: 5380

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

Upvotes: 8

Related Questions