Text in UITextField moves up after editing (center while editing)

前端 未结 13 1093
执念已碎
执念已碎 2020-12-01 03:14

I have a strange problem. I have an UITextField in which the user should write the amount of something, so the field is called \"amountField\". Everything looks fine, when t

相关标签:
13条回答
  • 2020-12-01 04:11

    This is because the BaselineOffset for the textfield got changed. In UITextFieldDidEndEditing creating an attributed text with NSBaselineOffset: 0 and using that attributedText would fix the problem.

    -(IBAction)txtFieldDidEndEditing:(UITextField *)sender {
         NSDictionary *style = @{
                                NSBaselineOffsetAttributeName: @(0)
                                };
        self.txtField.attributedText = [[NSAttributedString alloc] initWithString:self.txtField.text attributes:style];
    }
    
    0 讨论(0)
  • 2020-12-01 04:12

    I fixed this by adding height constraints to my UITextFields.

    0 讨论(0)
  • 2020-12-01 04:14

    This bug happened to me when I set text & became the first responder in viewDidLoad or viewWillAppear. When I moved the becomeFirstResponder code to viewDidAppear the bug went away.

    0 讨论(0)
  • 2020-12-01 04:14

    I wasn't able to change the font file, so when I solved this I saved the original UITextField's frame in a property and applied the following code:

    - (void)textFieldDidBeginEditing:(UITextField *)textField
    {
        textField.frame = self.usernameFrame;
    }
    
    - (void)textFieldDidEndEditing:(UITextField *)textField
    {
        textField.frame = CGRectOffset(self.usernameFrame, 0, 1);
    }
    

    It's a bit hacky, but it gets the job done.

    0 讨论(0)
  • 2020-12-01 04:15

    So...

    After many hours of trying many things - I have found the problem. In my case the problem is the font. I really don't know why, but the author of the font made the font weird (leading etc.), it has a blank space on the bottom. I don't know why, but when you are editing the text all of the text properties are ignored, but after you finish editing, they are applied.

    So, if you have a similar problem, try changing the font to Arial or something similar.

    For a full explanation, please consult these following links: link 1 and link 2. The solution recommended in these links can avoid you a lot of headaches and can even be applied to fix problem like text moving to the top when you start editing an UITextField (using System font or other particular fonts).

    0 讨论(0)
  • 2020-12-01 04:15

    Disabling ClipsToBounds for the TextField solved it for me.

    0 讨论(0)
提交回复
热议问题