在viewDidAppear中调用未添加约束的调用

时间:2016-12-08 01:31:53

标签: ios swift constraints

在我的代码中,我有一个viewWillAppear调用,就像下面设计的那样,可以将某些对象移开。

override func viewWillAppear(_ animated: Bool) {
        playButton.center.x -= view.bounds.width
        howToButton.center.x -= view.bounds.width
        imageView1.center.x = view.bounds.width - (imageView1.frame.width / 2)
        imageView2.center.x = view.bounds.width - (imageView2.frame.width / 2)
        imageView1.center.x += imageView1.frame.width
        imageView2.center.x += imageView2.frame.width
        introductoryLabel.alpha = 0
    }

接下来是一个viewDidAppear调用,它将这些对象设置为场景。我的问题是viewDidAppear执行动画(它基本上反转了viewWillAppear中的内容),就像没有调用viewWillAppear一样。有趣的是,当我在故事板中应用约束时,这只是一个问题。如何保留约束但允许viewDidAppear执行它的操作?

任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:1)

  

有趣的是,当我在故事板中应用约束时,这只是一个问题

这一点都不奇怪。如果您已应用约束,则无法然后更改视图的center。嗯,你可以,但这样做是没用的,因为约束将继续根据约束重新定位它们。毕竟,这是约束的目的

所以,基本上,有两种方法可以定位:一方面使用framecenter,另一方面使用约束。不要试图将它们混合在一起。使用其中一种。

答案 1 :(得分:0)

我不确定这会有所帮助,但您应该像这样调用super.viewDidAppear(动画):

    override func viewWillAppear(_ animated: Bool) {

            super.viewWillAppear(animated) // This is what you may be missing

            playButton.center.x -= view.bounds.width
            howToButton.center.x -= view.bounds.width
            imageView1.center.x = view.bounds.width - (imageView1.frame.width / 2)
            imageView2.center.x = view.bounds.width - (imageView2.frame.width / 2)
            imageView1.center.x += imageView1.frame.width
            imageView2.center.x += imageView2.frame.width
            introductoryLabel.alpha = 0
        }

答案 2 :(得分:0)

来自Xib或Storyboard的视图仍在willWillApearwillDidApear方法中重新定位,因此您无法更改视图的框架。如果你真的想这样做,请在延迟一段时间后更改它们,例如。 0.25s,或者您可以在viewDidLayoutSubViews方法中更改它们。(不推荐,多次调用)。此外,您可以通过更改view.transform或更改约束来为视图设置动画。

相关问题