xcode 编辑后 UITextField 中的文本向上移动(编辑时居中)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9674566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 23:37:14  来源:igfitidea点击:

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

iphoneobjective-ciosxcodeuitextfield

提问by Dominik Hadl

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 the user starts editing the textfield the text is in the vertical and horizontal center - that's great.

我有一个奇怪的问题。我有一个 UITextField,用户应该在其中写一些东西的数量,所以这个字段被称为“amountField”。一切看起来都很好,当用户开始编辑文本字段时,文本位于垂直和水平中心 - 这很棒。

However, when the user ends editing the text moves up a little bit. I tried many things, nothing helped...

但是,当用户结束编辑时,文本会向上移动一点。我尝试了很多东西,没有任何帮助...

I am adding screenshots below, so you can see what is the problem.

我正在下面添加屏幕截图,以便您可以看到问题所在。

This is what it looks like while editing the field - that's ok.

这就是编辑字段时的样子 - 没关系。

This is while editing the field - that's ok.

这是在编辑字段时 - 没关系。

And this is how it looks when done editing - that is the problem!

这就是完成编辑后的样子——这就是问题所在

This is the problem.

这就是问题。

Please, if anybody know what could cause this I would be very grateful! :)

拜托,如果有人知道可能导致这种情况的原因,我将不胜感激!:)

Here is some of my code related to the amountField.

这是我的一些与 amountField 相关的代码。

amountField.keyboardType = UIKeyboardTypeNumberPad;
amountField.returnKeyType = UIReturnKeyDone;
amountField.delegate = self;

[amountField setFont:[UIFont fontWithName:@"Nuptial Script LT Std" size:30]];   
amountField.borderStyle = UITextBorderStyleNone;
UIImage *amountBg = [UIImage imageNamed:@"skin2_ipad_amountField.png"];
[amountField setBackground:amountBg];

amountField.rightView = nil;
//amountField.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.2];

amountField.textAlignment = UITextAlignmentCenter;
amountField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
amountField.adjustsFontSizeToFitWidth = YES;
amountLabel.textColor = UIColorFromARGB(0x313030); //Using my own macro

amountField.frame = CGRectMake(300, 480, 136, 32);
amountField.center = CGPointMake(605, 439);

PS: Those white corners are there because I set the background to white with 0.2 alpha, that's ok.

PS:那些白角在那里是因为我用 0.2 alpha 将背景设置为白色,没关系。

采纳答案by Dominik Hadl

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.

因此,如果您遇到类似的问题,请尝试将字体更改为 Arial 或类似的字体。

For a full explanation, please consult these following links: link 1and 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).

如需完整说明,请参阅以下链接:链接 1链接 2。这些链接中推荐的解决方案可以避免您很多麻烦,甚至可以应用于解决问题,例如当您开始编辑 UITextField(使用系统字体或其他特定字体)时文本移动到顶部。

回答by n8tr

I had a similar issue that started happening on iOS 9. Basically I have a UITextField in a collection view cell. Sometimes when the user is done typing and editing ends, the text "bounces" up then down again into its correct position. Very strange and annoying glitch. Simply making this tweak fixed the issue on iOS 9 and proved to be safe on iOS 7 and 8:

我有一个类似的问题,开始发生在iOS 9 上。基本上我在集合视图单元格中有一个 UITextField 。有时,当用户完成输入和编辑结束时,文本“弹跳”然后再次回到正确的位置。非常奇怪和烦人的故障。只需进行此调整即可解决 iOS 9 上的问题,并证明在 iOS 7 和 8 上是安全的:

 - (void)textFieldDidEndEditing:(UITextField *)textField
 {
    [textField layoutIfNeeded]; //Fixes iOS 9 text bounce glitch
    //...other stuff
}

回答by Alexis Candelaria

Disabling ClipsToBounds for the TextField solved it for me.

为 TextField 禁用 ClipsToBounds 为我解决了这个问题。

回答by skr1p7k1dd

This bug happened to me when I set text & became the first responder in viewDidLoador viewWillAppear. When I moved the becomeFirstRespondercode to viewDidAppearthe bug went away.

当我设置文本并成为viewDidLoad或 中的第一响应者时,这个错误发生在我身上viewWillAppear。当我将becomeFirstResponder代码移到viewDidAppear错误上时就消失了。

回答by JakubKnejzlik

I'm struggling with this issue almost every time when the design of app is with custom font. One option is to fix the font (but this is too much work – at least for me :) ). The second option I'm using is subclassing the UITextField and overriding the editingRectForBounds: and placeholderRectForBounds: methods and correct the offset. It should work for your case too.

当应用程序的设计使用自定义字体时,我几乎每次都在努力解决这个问题。一种选择是修复字体(但这工作量太大——至少对我来说:))。我使用的第二个选项是子类化 UITextField 并覆盖 editRectForBounds: 和 placeholderRectForBounds: 方法并更正偏移量。它也应该适用于您的情况。

@implementation MyTextFieldWithFixedFontPosition

-(CGRect)editingRectForBounds:(CGRect)bounds{
    return CGRectOffset([self textRectForBounds:bounds], 0, 0.5); //0.5 is just example, you can adjust to any offset you like
}
-(CGRect)placeholderRectForBounds:(CGRect)bounds{
    return [self editingRectForBounds:bounds];
}

@end

I haven't tested it with leftView or rightView though, so be careful when using these :)

我还没有用 leftView 或 rightView 测试过它,所以使用这些时要小心:)

NOTE: this approach is "font dependant", values used for offset may vary for each font and size

注意:这种方法是“字体相关的”,用于偏移的值可能因每种字体和大小而异

回答by King-Wizard

There is a glitch on iOS 8.1 and below, I do not know if they will fix it later but at that time there is not an unique solution which fixes all cases, because the bug and the solutions are font's type, size dependent.

iOS 8.1 及以下版本存在小故障,我不知道他们以后是否会修复它,但当时还没有解决所有情况的唯一解决方案,因为错误和解决方案取决于字体的类型和大小。

One of this solution or a combination of these solutions below can fix your problem:

以下解决方案之一或这些解决方案的组合可以解决您的问题:

  • Changing the font's size.

  • Changing the font's type.

  • Changing the UITextField's size.

  • Decompiling the font in question, modifying the font's characteristics and recompiling it (for more explanation please consult the following links: link 1and link 2).

  • 改变字体的大小。

  • 改变字体的类型。

  • 更改 UITextField 的大小。

  • 反编译有问题的字体,修改字体特性并重新编译(更多解释请参考以下链接:链接 1链接 2)。

Otherwise this other self-sufficient solution below can fix your problem:

否则,下面的其他自给自足的解决方案可以解决您的问题:

Swift version

迅捷版

import UIKit

class CustomTextField: UITextField {

    ...

    override func textRectForBounds(bounds: CGRect) -> CGRect {
        // Possible values.
        return CGRectInset(bounds, CGFloat(35.0), CGFloat(0.0))
    }

    override func editingRectForBounds(bounds: CGRect) -> CGRect {
        // Possible values.
        return CGRectInset(bounds, CGFloat(35.0), CGFloat(0.0))
    }

    override func placeholderRectForBounds(bounds: CGRect) -> CGRect {
        // Possible values.
        return CGRectInset(bounds, CGFloat(35.0), CGFloat(0.0))
    }

}

This solution has been tested with leftView and works like a charm.

这个解决方案已经过 leftView 测试,效果很好。

NOTE: this approach is "font dependant", values used for CGRectInset may vary for each font and size.

注意:这种方法是“字体相关的”,用于 CGRectInset 的值可能因每种字体和大小而异。

回答by Christopher Garcia

I fixed this by adding height constraints to my UITextFields.

我通过向 UITextFields 添加高度约束来解决这个问题。

回答by kdvijay

This is because the BaselineOffset for the textfield got changed. In UITextFieldDidEndEditingcreating an attributed text with NSBaselineOffset: 0 and using that attributedTextwould fix the problem.

这是因为文本字段的 BaselineOffset 已更改。在UITextFieldDidEndEditing创建具有NSBaselineOffset的属性文本:0和使用attributedText将解决这个问题。

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

回答by rollingstoneW

These solution above doesn't work for me.My solution is subclass UITextField and override setText:

上面的这些解决方案对我不起作用。我的解决方案是子类 UITextField 并覆盖 setText:

- (void) setText:(NSString *)text {
    [super setText:text];
    [self layoutIfNeeded];
}

回答by Gilbertat

Check the keyboard to change the view of the position of the pop-up if there is line of code self.view.layoutIfNeeded()Delete it.Good Luck!

检查键盘以更改弹出窗口位置的视图,如果有代码行self.view.layoutIfNeeded()删除它。祝你好运!