我在用于选择日期的容器中对齐了三个 UITextField。
起初只有月份文本框显示在容器中并占据整个宽度,然后当用户选择月份时,日期文本框出现并且它们都占据了容器的一半。
这些文本字段中的文本对齐是居中的。
我的问题是,当我设置它们的大小动画时,文本不会设置动画并直接跳到最终位置,而文本字段的宽度正确设置动画。
第 2 步:TexField 宽度是动态的,但文本已经在最终位置
我的代码用于为约束设置动画:
monthTextfieldTrailingConstraint.priority = currentDateSelectionType == .month ? UILayoutPriorityDefaultHigh : UILayoutPriorityDefaultLow
dayTextfieldTrailingConstraint.priority = currentDateSelectionType == .day ? UILayoutPriorityDefaultHigh : UILayoutPriorityDefaultLow
yearTextfieldTrailingConstraint.priority = currentDateSelectionType == .year ? UILayoutPriorityDefaultHigh : UILayoutPriorityDefaultLow
UIView.animate(withDuration: nextStepAnimationDuration) {
self.layoutIfNeeded()
}
最佳答案
我有几乎完全相同的问题。请参阅我的问题及其答案以供引用:UITextField text jumps when animating width constraint
解决方案演示
解决方案是将文本字段嵌入另一个 View (例如另一个 UITextField 或 UIView)。在下面的 gif 中,我在文本字段中放置了一个文本字段。请注意,helloWorldTextField
有一个蓝色边框以显示其在其后的第二个文本字段中的位置。
说明
- 对于每个字段(月、日),创建两个文本字段,例如
monthTextField
和monthBorderTextField
。 - 移除
monthTextField
的边框和背景颜色。保留borderTextField
的边框和背景颜色。 - 在
borderTextField
中将monthTextField
居中。 - 根据需要为
borderTextField
的宽度设置动画。
Github 链接和代码
这是我在 Github 上的项目的链接:https://github.com/starkindustries/ConstraintAnimationTest
这是我的 MyViewController 类测试项目的代码。其他一切都在 Storyboard中设置,可以在上面的链接的 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)
}
}
注释和引用
@JimmyJames 的评论让我想到了这个解决方案:“您只是在为 UITextField 宽度设置动画,但里面的内容没有动画。”
我研究了如何为字体变化设置动画并遇到了这个问题:Is there a way to animate changing a UILabel's textAlignment?
在那个问题中,@CSmith 提到“您可以为 FRAME 而不是 textAlignment 设置动画”https://stackoverflow.com/a/19251634/2179970
该问题中接受的答案建议在另一个框架内使用 UILabel。 https://stackoverflow.com/a/19251735/2179970
关于ios - UITextfield 文本位置在宽度约束动画时不动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40090644/