我在用于选择日期的容器中对齐了三个UITextField。
首先,只有月份文本字段显示在容器中并占据整个宽度,然后当用户选择月份时,显示日期文本字段并且它们都占用容器的一半。
这些文本域中的文本对齐集中在一起。
我的问题是,当我为其大小设置动画时,文本没有动画并直接跳转到最终位置,同时文本字段的宽度正确生成。
我的代码用于为约束设置动画:
monthTextfieldTrailingConstraint.priority = currentDateSelectionType == .month ? UILayoutPriorityDefaultHigh : UILayoutPriorityDefaultLow
dayTextfieldTrailingConstraint.priority = currentDateSelectionType == .day ? UILayoutPriorityDefaultHigh : UILayoutPriorityDefaultLow
yearTextfieldTrailingConstraint.priority = currentDateSelectionType == .year ? UILayoutPriorityDefaultHigh : UILayoutPriorityDefaultLow
UIView.animate(withDuration: nextStepAnimationDuration) {
self.layoutIfNeeded()
}
答案 0 :(得分:2)
我几乎有完全相同的问题。请参阅我的问题及其答案以供参考:UITextField text jumps when animating width constraint
解决方案演示
解决方案是将文本字段嵌入另一个视图中(例如,另一个UITextField或UIView)。在下面的gif中,我在文本字段中放置了一个文本字段。请注意helloWorldTextField
有一个蓝色边框,以显示其位于其后面的第二个文本字段中的位置。
<强>说明强>
monthTextField
和monthBorderTextField
。monthTextField
的边框和背景颜色。保留borderTextField
的边框和背景颜色。 monthTextField
内borderTextField
。 borderTextField
的宽度设置动画。Github链接和代码
以下是我在Github上的项目的链接:https://github.com/starkindustries/ConstraintAnimationTest
以下是我的MyViewController类的测试项目的代码。其他所有内容都在故事板中设置,可以在上面链接的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的评论:&#34;你只是设置了UITextField宽度的动画,但里面的内容没有动画。&#34;
我研究了如何设置字体更改动画,并遇到了这个问题:Is there a way to animate changing a UILabel's textAlignment?
在那个问题中@CSmith提到&#34;你可以为FRAME设置动画,而不是textAlignment&#34; https://stackoverflow.com/a/19251634/2179970
该问题中接受的答案建议在另一帧内使用UILabel。 https://stackoverflow.com/a/19251735/2179970