Reputation: 205
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
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
Reputation: 25740
I would use the UITextFieldDelegate
method that was made just for this.
Make your view controller adopt this protocol. i.e. in your .h file:
@interface YourViewController : UIViewController <UITextFieldDelegate> {
In Interface Builder, set the delegate
of textInput
to your view controller.
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
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