Billy Goswell
Billy Goswell

Reputation: 205

Why is my IBAction to change the text of a label not working?

I want to implement a label in my iOS app that changes its value to that of a text field when the user types a new character into the text field.

Hence, I wrote this IB Action in my view controller. listenerLabel is a UILabel IBOutlet, and textInput is a UITextField IBOutlet.

- (IBAction)keyboardResponse:(id)sender
{
    listenerLabel.text = textInput.text;
}

I then declared it in my header file.

- (IBAction)keyboardResponse:(id)sender;

Afterwards, in my xib file, I

  1. dragged a line from File's Owner to the two UI elements and associated them with the IBOutlets.
  2. hit Ctrl and clicked on the text field in the UIBuilder to associate its "Value Changed" action to the IBAction keyboardResponse.

However, when I run the app in iOS Simulator, the text of the label does not change as I type letters into the text field. Why not?

Upvotes: 3

Views: 1405

Answers (2)

lnafziger
lnafziger

Reputation: 25740

I would use the UITextFieldDelegate method that was made just for this.

  1. Make your view controller adopt this protocol. i.e. in your .h file:

    @interface YourViewController : UIViewController <UITextFieldDelegate> {

  2. In Interface Builder, set the delegate of textInput to your view controller.

  3. Then in your .m file, add the following: (EDITED)

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
        if (textField == textInput) {
            listenerLabel.text  = [textField.text stringByReplacingCharactersInRange:range withString:string];;
        }
        // Note that if you don't want the characters to change in the textField 
        // you can return NO here:
        return YES;
    }
    

Upvotes: 1

LJ Wilson
LJ Wilson

Reputation: 14427

You need to use a notification to do this. Assuming you have those outlets wired up correctly to both the label and the textfield do this:

in viewDidLoad:

[[NSNotificationCenter defaultCenter] 
     addObserver:self 
     selector:@selector(myTextChanged)
     name:UITextFieldTextDidChangeNotification 
     object:textInput];

Add this method (you don't need those IBActions

-(void)myTextChanged {
    self. listenerLabel.text = textInput.text;

}

As a side-note - learn to use the Assistant Editor, it eliminates mistakes when wiring up IBActions or IBOutlets and adds in the cleanup in the viewDidUnload automagically.

Upvotes: 3

Related Questions