为什么每次点击 UITextField 时都会调用 viewDidLayoutSubviews [英] Why is viewDidLayoutSubviews called everytime a UITextField is tapped
问题描述
我有一个 viewController
,它包含一个 view
,里面有四个 UITextFields
.我想要做的是在 ViewController 加载后立即为视图设置动画.
I have a viewController
that contains a view
with four UITextFields
inside of it. What I'm trying to do is animate the view as soon as the ViewController is loaded.
当控制器加载时动画按我想要的方式工作,但由于某种原因 viewDidLayoutSubviews
每次点击任何 UITextFields
时都会被调用,因此它会继续为视图设置动画.
The animation works the way I want when the controller is loaded but for some reason viewDidLayoutSubviews
gets called every time I tap any of the UITextFields
so it keeps animating the view.
这是正常行为吗,每次点击 TextField 时都应该调用 viewDidLayoutSubviews 吗?
Is this normal behavior, is viewDidLayoutSubviews supposed to get called every time a TextField is tapped?
这是我的代码:
class MyViewController: UIViewController{
@IBOutlet weak var viewAlertContainer: UIView!
override func viewDidLayoutSubviews() {
showAlertViewWithAnimation()
}
func showAlertViewWithAnimation(){
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 2, options: .curveEaseIn, animations: {
self.viewAlertContainer.frame.origin.y = 150
})
}
}
推荐答案
viewDidLayoutSubviews()
将在 Auto Layout 认为它有工作要做的任何时候被调用,这可能发生在你意想不到的时候.这使得执行一次发生的操作成为一个糟糕的选择.
viewDidLayoutSubviews()
will be called anytime Auto Layout thinks it has work to do, and that may happen at times you don't expect. This makes it a poor choice to perform actions that occur once.
将您的动画移动到 viewDidAppear()
的覆盖.这是您第一次知道可以看到视图,因此是执行动画的合适位置.
Move your animation to an override of viewDidAppear()
. That is the first time you know the views are able to be seen, and thus an appropriate place to perform the animation.
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
showAlertViewWithAnimation()
}
这篇关于为什么每次点击 UITextField 时都会调用 viewDidLayoutSubviews的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!