Reputation: 2374
I've used UITextfield inside Tableview's cell using the following code:
- (UITextField *)textFieldWithDefaultsForCell:(int)cellIdentifier {
UITextField *textField = [[[UITextField alloc] initWithFrame:CGRectMake(180, 12, 135, 20)] autorelease];
textField.autocorrectionType = UITextAutocorrectionTypeNo;
textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
textField.delegate = self;
textField.textColor = [UIColor colorWithRed:66.0/225.0 green:77.0/255.0 blue:103.0/255.0 alpha:1.0];
textField.returnKeyType = UIReturnKeyDone;
textField.tag = cellIdentifier;
textField.placeholder = @"Enter text";
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom;
textField.clearButtonMode = UITextFieldViewModeWhileEditing;
return textField;
}
and then,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
....
....
switch (indexPath.row) {
case EmailAddressCellIdentifier:
cell.textLabel.text = @"Email Address";
textField.keyboardType = UIKeyboardTypeEmailAddress;
textField.text = configurator.emailAddress;
[emailAddressField release];
emailAddressField = [textField retain];
[cell.contentView addSubview:textField];
break;
....
....
}
Now, please see the following image:
In the email box, I was typing abcdef-123456789... But the view is stuck. It doesn't move to right and I can't see the rest of the text (6789...). I can only see abcdef-12345
Can you please tell me, where is the error?
Upvotes: 3
Views: 3080
Reputation: 1673
Change the line:
UITextField *textField = [[[UITextField alloc] initWithFrame:CGRectMake(180, 12, 135, 20)] autorelease];
To:
UITextField *textField = [[[UITextField alloc] initWithFrame:CGRectMake(135, 12, 180, 20)] autorelease];
Your textfield's frame width (the third parameter in CGRectMake()) is too small to hold the text.
As an aside, if the form will not be dynamic, consider creating static cells in storyboard rather than dynamically populating the table. Typically, if you have a large switch statement in your cellForRowAtIndexPath: method, a static table is calling your name.
EDIT 1
You can also create the text field's frame setting the its x as a certain distance from the accompanying label via:
CGRectMake(label.bounds.size.width + paddingBetweenTextFieldAndLabel, 12, 135, 20)
We can even expand on this concept by setting the textfields height and width based on cell dimensions:
CGFloat textFieldX = label.bounds.size.width + paddingBetweenTextFieldAndLabel;
CGRectMake(textFieldX,
label.frame.origin.y,
cell.bounds.size.width - (textFieldX),
cell.bounds.size.height)
If you pass the label of the textfield as a parameter in your method:
- (UITextField *)textFieldWithDefaultsForCell:(int)cellIdentifier
The above code should work.
EDIT 2
If you are worried about the text showing up on the right, set its alignment:
textField.textAlignment = NSTextAlignmentRight;
Upvotes: 3