Using a custom font in a UITextField causes it to shift slightly when accessed — is there a fix?

前端 未结 10 1963
后悔当初
后悔当初 2020-12-13 14:32

I have a custom font in a UITextField, and I\'ve noticed that when it\'s accessed (when the keyboard appears), the text shifts down by a very small amount -- maybe

相关标签:
10条回答
  • 2020-12-13 14:54

    Works for all font sizes and does not cause de-alignment with clearButton.

    Subclass UITextField and override these as follows:

    - (CGRect)placeholderRectForBounds:(CGRect)bounds
    {
        return CGRectOffset( bounds, 0, 4 );
    }
    
    - (CGRect)editingRectForBounds:(CGRect)bounds
    {
        return CGRectOffset( bounds, 0, 2);
    }
    
    - (CGRect)textRectForBounds:(CGRect)bounds
    {
        return CGRectOffset( bounds , 0 , 4 );
    }
    
    0 讨论(0)
  • 2020-12-13 14:55

    You should set Font property earlier than Text property.

    0 讨论(0)
  • 2020-12-13 14:58

    My solution is along the same lines a McDJ's, but with a slightly different twist. Subclass UITextField and override only these:

    - (CGRect)placeholderRectForBounds:(CGRect)bounds {
      return CGRectOffset( [self editingRectForBounds:bounds], 0, 2 );
    }
    
    - (CGRect)editingRectForBounds:(CGRect)bounds {
      return CGRectOffset( [super editingRectForBounds:bounds], 0, -2 );
    }
    

    With the custom font I'm using, 2 points is the correct vertical adjustment, helping placeholder, "static", and "editing" text all stay on the same vertical line.

    0 讨论(0)
  • 2020-12-13 15:03

    I had this issue as well.

    To fix, subclass UITextField and implement the following methods to adjust the positioning of text when not editing and editing.

    - (CGRect)textRectForBounds:(CGRect)bounds {
    
        return CGRectInset( bounds , 8 , 8 );
    }
    
    - (CGRect)editingRectForBounds:(CGRect)bounds {
    
        return CGRectInset( bounds , 8 , 5 );
    }
    
    0 讨论(0)
提交回复
热议问题