iPad UITextField — cursor not centering when resizing frame with contentVerticalAlignment = UIControlContentVerticalAlignmentCenter

大城市里の小女人 提交于 2020-01-04 05:19:08

问题


I am working on a universal iPhone/iPad app. I resize some of my UITextFields as the user types. I also have some code to move the UITextFields around so that their locations make sense as they are resized. This code is not too short, but basically it comes down to modifying the frames of the UITextFields.

My UITextFields all have their content vertically centered by setting

textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;

The text centers just fine. But when I resize the textfield on the iPad, the cursor sometimes goes to the top of the box. This looks strange to the user as the text is in the center.

This always happens on the iPad, never on the iPhone. Making matters worse, I can't isolate which particular part of the code causes it to happen -- except that if I stop resizing things, the problem goes away.

Has anyone else ever encountered this? Were you able to isolate the source of the problem?

Thanks.


回答1:


I figured out what triggers the bug. It happens when textField is resized both by layoutSubviews and by a method triggered by UIControlEventEditingChanged.




回答2:


For better control of text field text alignment you can use subclass of UITextField where you override following methods:

- (CGRect)textRectForBounds:(CGRect)bounds
{
    CGRect rect = [super textRectForBounds:bounds];
    rect.origin.y = (bounds.size.height - rect.size.height) / 2;
    rect = CGRectInset(rect, 3.0f, 0.0f);
    return rect;
}

- (CGRect)editingRectForBounds:(CGRect)bounds
{
    CGRect rect = [super editingRectForBounds:bounds];
    rect.origin.y = (bounds.size.height - rect.size.height) / 2;
    rect = CGRectInset(rect, 3.0f, 0.0f);
    return rect;
}

- (CGRect)placeholderRectForBounds:(CGRect)bounds
{
    CGRect rect = [super placeholderRectForBounds:bounds];
    rect.origin.y = (bounds.size.height - rect.size.height) / 2;
    rect = CGRectInset(rect, 3.0f, 0.0f);
    return rect;
}


来源:https://stackoverflow.com/questions/4025593/ipad-uitextfield-cursor-not-centering-when-resizing-frame-with-contentvertica

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!