Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

iphone - Placeholder text not centered for UITextField created programmatically

I am creating a UITextField programmatically and placing it inside a UIView. The font size is set to 15.0f (system font). But the placeholder that appears is not centered in the text view. Any one know how to resolve this?

I found some references on SO for blurred text etc and tried setting the frame of the textfield with integer values, but it doesn't make a difference.

UITextField *txtField = [[UITextField alloc] initWithFrame:CGRectMake(5.0f, 6.0f, 278.0f, 32.0f)];
[txtField setPlaceholder:@"My placeholder"];
[txtField setFont:[UIFont systemFontOfSize:15.0]];
[txtField setBorderStyle:UITextBorderStyleRoundedRect];
[txtField setAutocorrectionType:UITextAutocorrectionTypeNo];
[txtField setAutocapitalizationType:UITextAutocapitalizationTypeNone];
[txtField setKeyboardType:UIKeyboardTypeEmailAddress];
[txtField setReturnKeyType:UIReturnKeyDone];
[txtField setClearButtonMode:UITextFieldViewModeWhileEditing];

Thank you for any help

Note: I mean that the text is not centered vertically in the textfield (it is a bit towards the top). So setting the text alignment is not the solution.

Adding an image of the issue for clarification - as seen in the image, the placeholder text is more towards the top and not in the center vertically. alt text

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to add:

txtField.textAlignment = NSTextAlignmentCenter; // Pre-iOS6 SDK: UITextAlignmentCenter

Keep in mind, this adjusts both the alignment of the placeholder text as well as the text the user will enter in.

How to center vertically

Since the original question was updated to request how to vertically align the placeholder text and that answer is buried in the comments, here is how to do that:

txtField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...