xcode viewDidAppear 和 viewDidLoad 初始化位置太晚了

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26554265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 05:59:20  来源:igfitidea点击:

viewDidAppear & viewDidLoad Are Are Initializing Positions Too Late

iosobjective-cxcodeswiftinterface-builder

提问by Aggressor

I am looking to update a UIView thats in a storyboard (and instantiated from the storyboard) when it loads in the app.

我希望在应用程序中加载时更新故事板中的 UIView(并从故事板实例化)。

I need to position a few icons in a dynamic way (that the interface builder doesn't let me do quite yet). However, if I put my code in viewDidAppear or viewDidLoad, it seems to be getting called too late.

我需要以动态方式放置一些图标(界面构建器还不允许我这样做)。但是,如果我将代码放在 viewDidAppear 或 viewDidLoad 中,它似乎被调用为时已晚。

Here is what happens the first few second or two when the view loads:

这是视图加载时的前几秒或两秒发生的情况:

initial load

initial load

And then a bit later it goes to the right position (as the code was called).

然后稍后它会到达正确的位置(正如代码所调用的那样)。

Fixed position a second later

Fixed position a second later

My question is where do I need to initialize the positions of these objects so they dont snap over a second later. viewDidLoad and viewDidAppear are too late? Why!? :)

我的问题是我需要在哪里初始化这些对象的位置,以便它们不会在一秒钟后捕捉到。viewDidLoad 和 viewDidAppear 为时已晚?为什么!?:)

override func viewDidAppear(animated: Bool)
{
    initView()
    _gridLines = false

}

func initView()
{
    _cameraFeed.initAfterLoad()
    //center the buttons on half distance between middle button and screen edge
    var middleDistance:CGFloat = _swapButton.frame.origin.x + _swapButton.frame.width/2
    _linesButton.frame.origin.x = middleDistance/2 - _linesButton.frame.width/2
    _flashButton.frame.origin.x = middleDistance + middleDistance/2 - _flashButton.frame.width/2
    _selectPhotos.frame.origin.x = middleDistance/2 - _selectPhotos.frame.width/2
}

Swift and objc answers welcome!

欢迎使用 Swift 和 objc 回答!

回答by SefTarbell

Try putting the code setting the frame in viewWillAppear instead of viewDidAppear.

尝试将设置框架的代码放在 viewWillAppear 而不是 viewDidAppear 中。

Also, you should call the super.

另外,你应该打电话给超级。

override func viewWillAppear(animated: Bool) {
    initView()
    _gridLines = false

    super.viewWillAppear(animated)
}