UITextField 子类的动画位置时文本跳转

Text jumps when animating position of UITextField subclass

当我为我的 UITextField 子类的位置设置动画时,字段中的文本与 UITextField 持有它的位置不一致,这非常刺耳,我不能找出它发生的原因:

我的子类在文本字段的右侧添加了一个按钮,当点击该按钮时会调用视图控制器上的一个方法,该方法会更改文本字段的边框颜色并通过更改顶部将文本字段向上移动 space 文本字段的约束,以及位于其上方的其他几个视图。

[UIView animateWithDuration:0.3
                     animations:^{
                         self.tableViewBottomSpaceConstraint.constant = 0;
                         self.mainLabelHeightConstraint.constant = 0;
                         self.subLabelTopSpaceConstraint.constant = 0;
                         self.postCodeFieldTopSpaceConstraint.constant = 12;
                         [self.view layoutIfNeeded];

                     }];

我解决了这个问题。将您的代码更改为此。它会起作用。

[UIView animateWithDuration:0.3
                 animations:^{
                     self.tableViewBottomSpaceConstraint.constant = 0;
                     self.mainLabelHeightConstraint.constant = 0;
                     self.subLabelTopSpaceConstraint.constant = 0;
                     self.postCodeFieldTopSpaceConstraint.constant = 12;
                     [self.view layoutSubviews];

                 }];

或者,如果这不起作用,则代替

[self.view layoutSubviews];

使用文本字段的父视图和布局子视图。就我而言,这很有效。我认为这个答案有资格获得赏金。谢谢

编辑:

我找到了原因。当我们尝试 layoutIfNeeded 时,这意味着它首先更改外部布局,然后在更改其布局后更改 UITextField 的内部文本,因为我们没有强制更改该文本字段的所有子视图的布局。毕竟 UITextField 是由 UIView 和 Label 以及其他基本元素组成的。但是当我们尝试 layoutSubviews 它同时改变所有子视图的布局时。这就是弹跳消失的原因。

由于某种原因,您的 UI 似乎在动画触发前未处于稳定状态。

尝试在动画块之前添加对 [self.view layoutIfNeeded]; 的调用,并在块的末尾使用 [self.view layoutIfNeeded]; 而不是在此上下文中不应真正使用的 [self.view layoutSubviews]; .

对于iOS 9或以上,这解决了问题

Objective-C:

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

Swift:

  func textFieldDidEndEditing(_ textField: UITextField) {
    textField.layoutIfNeeded() //Fixes iOS 9 text bounce glitch
    //...other stuff
  }

Google 带我到这里。在@Mahesh Agrawal 的回答下,@Andy 将 link 的 link 评论为 Here,这是我能找到的针对此问题的最佳解决方案。