In my custom table cell I want to show some default text in my UITextField like "enter your name" and when user starts to edit the cell I want that text stays there and un-editable, and the editi开发者_运维百科ng starts just where the default text ends. Can I do this easily?
I can do that by putting a label on the left and a textfield on the right, but then I have to calculate eachtime how long is the default text(which can be different for each field) and custom create a textfield in that lenght to fit in.
Any suggestions?
I have the label calculate the size. Just set the label's text then have the label size to fit, and slide the UITextField right up to the edge of the label. If I have a trailing space in the label's text it looks great.
Something like this:
UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 550.0, 28.0)];
[nameLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:24.0]];
[nameLabel setText:@"Name: "];
[nameLabel sizeToFit];
[self addSubview:nameLabel];
[nameLabel release];
UITextField *nameTextField = [[UITextField alloc] initWithFrame:CGRectMake(nameLabel.frame.size.width + nameLabel.frame.origin.x, 0.0, 550.0 - nameLabel.frame.size.width, nameLabel.frame.size.height)];
Edit to answer the comment about special cases: In special cases such as very long labels you'll have to add additional code. For example you could check the width after the sizeToFit
call, and if it exceeds a certain width, rebuild the label with multiple lines, smaller font, etc. Unfortunately, if you need to account for special cases, you'll have to do extra coding work.
Since you're using a UITextField
, you can hook into the UITextFieldDelegate
delegate methods to check the text of the text field at different states. For example, when the UITextField
is becomes editable, and whenever the text in the text field is changed.
The two you might be interested in are:
- (void)textFieldDidBeginEditing:(UITextField *)textField
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
Using these, you can easily have the placeholder
property of UITextField
contain whatever text you would like to use, then when the user begins to edit the field, have textFieldDidBeginEditing:
fill in the textfield text with the placeholder text, then monitor the text at every character the user inputs using textField:shouldChangeCharactersInRange:replacementString:
to not let the user delete the placeholder text you've input for them manually.
精彩评论