【发布时间】:2017-08-23 02:55:56
【问题描述】:
在为文本字段的宽度约束设置动画时,我遇到了一个故障,我的 UITextField 的文本会跳转到其最终位置(它没有动画)。看看这个 gif:
点击“增长”按钮时,文本字段的宽度会增长。但是“hello world”会立即跳到中心而不是在那里滑行。当点击“缩小”按钮时,“hello world”会立即跳回左侧。
我的动画函数如下所示:
func animateGrowShrinkTextFields(grow: Bool) {
if grow {
UIView.animate(withDuration: 0.5, animations: {
self.widthConstraint.constant = 330
self.view.layoutIfNeeded()
}, completion: nil)
} else {
UIView.animate(withDuration: 0.5, animations: {
self.widthConstraint.constant = 100
self.view.layoutIfNeeded()
}, completion: nil)
}
}
我尝试了以下列表建议;他们都没有工作。
- 我在动画块之前和之内调用了
self.view.layoutIfNeeded()和self.helloWorldTextField.layoutIfNeeded(),如以下答案所示:https://stackoverflow.com/a/32996503/2179970 - 我尝试了
self.view.layoutSubviews和self.helloWorldTextField.layoutSubview,正如这个答案中所建议的那样:https://stackoverflow.com/a/30845306/2179970 - 也试过
setNeedsLayout()UITextField text jumps iOS 9 - 我什至尝试按照此处的建议更改字体:https://stackoverflow.com/a/35681037/2179970
- 我尝试了
resignFirstResponder(尽管我从未在我的测试中点击或编辑文本字段,所以它不应该涉及 firstResponder),如下所示:https://stackoverflow.com/a/33334567/2179970 - 我尝试继承 UITextField 如下所示:https://stackoverflow.com/a/40279630/2179970
- 我也尝试使用 UILabel 并得到了同样的跳跃结果。
下面的问题也和我的很相似,但还没有答案:UITextfield text position not animating while width constraint is animated
这是我在 Github 上的项目:https://github.com/starkindustries/ConstraintAnimationTest
【问题讨论】:
-
你试过评论
self.view.layoutIfNeeded()吗?通常,你不需要这个... -
@JimmyJames 是的,我有。如果没有
self.view.layoutIfNeeded(),整个 textField 将不会动画,而是会立即增长/缩小。 -
嗯,好的。然后我的坏^^。 Yourwidth 约束是
UITextField的宽度,对吗?而这个UITextField有一个text center属性? -
不用担心 :) 是的,是的。故事板中的初始宽度约束设置为 100。 UITextField textAlignment 也设置为故事板的中心。
-
我认为这很正常...您只是在为
UITextField宽度设置动画,但里面的内容没有动画...尝试使用您的动画搜索动画内容
标签: ios iphone swift animation