To create a form that resembles the Gmail form in the iPhone Mail application, create a UITableView and add a UITextField into each UITableViewCell.
You can download the source code for an example here:
What follows is a brief explanation of some parts of the code.
Source Explanation
Our controller class has fields to hold references to the UITextFields and their values when they are modified.
- @interface FormTableController : UITableViewController<UITextFieldDelegate> {
- NSString* name_ ;
- NSString* address_ ;
- NSString* password_ ;
- NSString* description_ ;
- UITextField* nameField_ ;
- UITextField* addressField_ ;
- UITextField* passwordField_ ;
- UITextField* descriptionField_ ;
- }
The makeTextField method creates a UITextField that resembles the ones used in the iPhone Mail application.
- -(UITextField*) makeTextField: (NSString*)text
- placeholder: (NSString*)placeholder {
- UITextField *tf = [[[UITextField alloc] init] autorelease];
- tf.placeholder = placeholder ;
- tf.text = text ;
- tf.autocorrectionType = UITextAutocorrectionTypeNo ;
- tf.autocapitalizationType = UITextAutocapitalizationTypeNone;
- tf.adjustsFontSizeToFitWidth = YES;
- tf.textColor = [UIColor colorWithRed:56.0f/255.0f green:84.0f/255.0f blue:135.0f/255.0f alpha:1.0f];
- return tf ;
- }
The makeTextField is then called in the cellForRowAtIndexPath method to create the text fields, which are then added as subviews of the
UITableCell
s.- cell.textLabel.text = @"Name" ;
- tf = nameField_ = [self makeTextField:self.name placeholder:@"John Appleseed"];
- [cell addSubview:nameField_];
The dimensions of the text field are also adjusted:
- // Textfield dimensions
- tf.frame = CGRectMake(120, 12, 170, 30);
When the value of any UITextField is changed, we save the new values by handling
textFieldDidEndEditing
.- // Textfield value changed, store the new value.
- - (void)textFieldDidEndEditing:(UITextField *)textField {
- if ( textField == nameField_ ) {
- self.name = textField.text ;
- } else if ( textField == addressField_ ) {
- self.address = textField.text ;
- } else if ( textField == passwordField_ ) {
- self.password = textField.text ;
- } else if ( textField == descriptionField_ ) {
- self.description = textField.text ;
- }
- }
Lastly, we dismiss the keyboard when the user taps Return by handling UIControlEventEditingDidEndOnExit.
- // Workaround to dismiss keyboard when Done/Return is tapped
- [tf addTarget:self action:@selector(textFieldFinished:) forControlEvents:UIControlEventEditingDidEndOnExit];
- // Workaround to hide keyboard when Done is tapped
- - (IBAction)textFieldFinished:(id)sender {
- // [sender resignFirstResponder];
- }