0

I'm trying to add UITextField input into an NSMutableArray using the following IBActions, connected to the 'did end editing' part of the UITextFields:

- (IBAction) returnKey1
{
    [textInputOne addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [textInputOne resignFirstResponder];
    [players addObject:textInputOne.text];
}

- (IBAction) returnKey2
{
    [textInputTwo addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [textInputTwo resignFirstResponder];
    [players addObject:textInputTwo.text];
NSLog(@"array: %@",players);
}

and I've initialized the players array in the viewDidLoad section like so:

- (void)viewDidLoad
{
    [super viewDidLoad];
    players = [[NSMutableArray alloc] init];
}

but the array remains 'nil'. Anyone know how to fix this?

Louis Holley
  • 135
  • 1
  • 3
  • 10

2 Answers2

2

UITextField doesn't send any actions when the user taps Return. So you won't receive the “did end editing” action when the user taps Return.

UITextField sends “did end editing” when it resigns first responder. You can make it resign first responder when the user taps Return by setting the text field's delegate and implementing textFieldShouldReturn:. Start by finding the class extension at the top of your ViewController.m. Edit it (or add it if it's not there) to declare that the class conforms to UITextFieldDelegate:

@interface ViewController () <UITextFieldDelegate>

@property (nonatomic, strong) IBOutlet UITextField *textFieldOne;
@property (nonatomic, strong) IBOutlet UITextField *textFieldTwo;

@end

Next, implement textFieldShouldReturn: in the class to make the text field resign first responder:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return NO;
}

Finally, in your xib, connect each text field's delegate outlet to the view controller (which is normally File's Owner).

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
1

I hope you have set the delegates to textfield properly. As you have allocated the players array in viewDidLoad try with following code

- (IBAction) returnKey1
{
    [players addObject:textInputOne.text];
}

- (IBAction) returnKey2
{
    [players addObject:textInputTwo.text];
}

Both returnKey1 & returnKey2 IBActions assigned to textfield did end editing events. Now to resign the key board

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

I tried the same thing in one sample project it worked well.

svrushal
  • 1,612
  • 14
  • 25