宽度约束animation时,UITextfield文本位置不animation

我有三个UITextField在用于selectdate的容器中alignment。

起初,只有月份的文本框显示在容器中,并占满了全部宽度,那么当用户select月份时,date文本框出现,并且它们都占用了一半的容器。

这些文本字段中的文本alignment处于居中状态。

我的问题是,当我animation的大小, 文字不animation和直接跳转到最后的位置,而文本域的宽度animation正确

第1步:animation之前的TextField 第1步:动画之前的TextField

第2步:TexField的宽度是animation,但文本已经在最后的位置 第2步:TexField的宽度是动画,但文本已经在最后的位置

第3步:TexField完成animation 第3步:TexField完成动画

我的代码用于animation约束:

monthTextfieldTrailingConstraint.priority = currentDateSelectionType == .month ? UILayoutPriorityDefaultHigh : UILayoutPriorityDefaultLow dayTextfieldTrailingConstraint.priority = currentDateSelectionType == .day ? UILayoutPriorityDefaultHigh : UILayoutPriorityDefaultLow yearTextfieldTrailingConstraint.priority = currentDateSelectionType == .year ? UILayoutPriorityDefaultHigh : UILayoutPriorityDefaultLow UIView.animate(withDuration: nextStepAnimationDuration) { self.layoutIfNeeded() } 

我几乎完全一样的问题。 请参阅我的问题和答案以供参考: animation宽度约束时,UITextField文本会跳转

解决scheme演示

解决scheme是将您的文本字段embedded到另一个视图(例如另一个UITextField或UIView)中。 在下面的GIF中,我把一个文本框放在一个文本框中。 请注意, helloWorldTextField有一个蓝色的边框,以显示它在其后的第二个文本字段中的位置。

在这里输入图像说明

说明

  1. 对于每个字段(月,日),创build两个文本字段,例如monthTextFieldmonthBorderTextField
  2. 删除monthTextField的边框和背景颜色。 保持borderTextField的边框和背景颜色。
  3. borderTextField monthTextField放置borderTextField
  4. 根据需要animationborderTextField的宽度。

Github链接和代码

这里是我的项目在Github上的链接: https : //github.com/starkindustries/ConstraintAnimationTest

这里是我的MyViewController类的testing项目的代码。 其他的一切都安装在故事板上,可以通过上面的链接在Github上查看。

 class MyViewController: UIViewController { // Hello World TextField Border var @IBOutlet weak var borderTextFieldWidth: NSLayoutConstraint! // Button Vars @IBOutlet weak var myButton: UIButton! var grow: Bool = false func animateGrowShrinkTextFields(grow: Bool, duration: TimeInterval) { if grow { UIView.animate(withDuration: duration, animations: { self.borderTextFieldWidth.constant = 330 self.view.layoutIfNeeded() }, completion: { (finished: Bool) in print("Grow animation complete!") }) } else { UIView.animate(withDuration: duration, animations: { self.borderTextFieldWidth.constant = 115 self.view.layoutIfNeeded() }, completion: { (finished: Bool) in print("Shrink animation complete!") }) } } @IBAction func toggle(){ let duration: TimeInterval = 1.0 grow = !grow let title = grow ? "Shrink" : "Grow" myButton.setTitle(title, for: UIControlState.normal) animateGrowShrinkTextFields(grow: grow, duration: duration) } } 

注释和参考

是什么导致我这个解决scheme是@ JimmyJames的评论:“你只是animation的UITextField宽度,但里面的内容是不animation。”

我研究了如何animation字体变化,并遇到这个问题: 有没有办法改变UILabel的textAlignmentanimation?

在那个问题@CSmith提到“你可以animation框架,而不是textAlignment” https://stackoverflow.com/a/19251634/2179970

在这个问题中接受的答案build议在另一个框架内使用UILabel。 https://stackoverflow.com/a/19251735/2179970