I have a very strange bug trying to horizontally center text in UITextField
object in iOS 7+ app.
I have set up a fresh project to isolate the bug and to make sure I'm not doing something wrong.
In viewDidAppear:
method I alloc/init a new UITextField
instance like this:
UITextField *tf = [[UITextField alloc] initWithFrame:CGRectMake(60.0f, 100.0f, 200.0f, 200.0f)];
tf.backgroundColor = [UIColor orangeColor];
tf.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:tf];
That's all. When I run this sample app on iPhone Retina (4-inch 64-bit) simulator I get following result:
After typing in some letters I get this:
Do anyone know what's is happening? The text should be centered while typing. I didn't come across this bug till now. It is iOS related or am I doing something wrong?
P.s.: It is happening on iDevices also.
Thanks in advance.
EDIT:
Adding:
tf.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
tf.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
doesn't help either.
EDIT 2:
Like Inder Kumar Rathore suggested I tried to set a height to 20.0f like so:
UITextField *tf = [[UITextField alloc] initWithFrame:CGRectMake(60.0f, 100.0f, 200.0f, 20.0f)];
and it surprisingly works. But it doens't solve the issue. I discovered that increasing height from 20.0f up makes issue only worse. I think it has something to do with line-height/text field height ratio. I don't know..
I think UITextField
expects the vertical size of the font to be equivalent to the height of the text field. If you imagine a font at a point size that will fill the vertical height of your text field at 200 points, you will only be able to type a few characters before it fills the horizontal width and switches from the centered behavior to the right-aligned behavior. This seems to be the behavior in your "bug" above, where you can only type a few characters before it switches behaviors.
I think the best thing to do is to make your text field just high enough to fit your font, and vertically center it in a containing UIView
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With