How can I read UITextField
value in an IBAction
? I\'m creating UITextField
programmatically. So I can\'t set @property
an
You could use something like this to loop through all UITextFields
that are subviews of self.view
and add their text to a NSMutableArray
:
for (UITextField *field in self.view.subviews) {
if ([field isKindOfClass:[UITextField class]]) {
if ([[field text] length] > 0) {
[someMutableArray addObject:field.text];
}
}
}
implement the IBAction function like the following:
-(IBAction) doneEditing:(UITextField*)sender
{
NSString * val = sender.text;
}
try using the UITextFieldDelegate , i think its better for your case.
add each UITextField a Tag and by that you will recognise the UITextField.
if your doneEditing:
looks like this doneEditing:(id)sender
then you can say:
UITextField *field = (UITextField *)sender;
NSString *myText = field.text;
EDIT:
To access a UITextField without setting as an instance variable you need to tag it when you create it:
[textField setTag:1];
then whenever you want to access it you can get it from its parent view by the tag:
UITextField *myTextField = [scroller viewWithTag:1];
NSString *myString = myTextField.text;
in your case, set the tag to i+1
for example to have all the textfield with unique tags.
NSString *value = sender.text;
If inside an IBAction, of course.
Which ignores that there is a set of text fields, and a single button action.
The simplest solution to the overall problem would be to store a set (or array) of text fields in an instance variable, and iterate over that set in the button action. But that is a rather coarse approach; it is probably better to use the text field delegate method and store text values directly in an array, using the button to trigger the save.
In addition, Apple HIG would tell you that you should update your data model as the text fields are edited, rather than use a "Save" button - which is poor UX design - unless, of course, the values of individual fields can interact.