xcode -viewWillLayoutSubviews 中调用的方法莫名其妙地运行了两次

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14946623/
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 02:48:08  来源:igfitidea点击:

Method called in -viewWillLayoutSubviews inexplicably runs twice

objective-cxcodecocoa-touch

提问by Dmitry Minkovsky

I've got the following code in a detail view controller:

我在详细视图控制器中有以下代码:

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    [self configureView];
}

When I segue to this view controller with a breakpoint on first line of -configureView, it appears that [self configureView]is called twice. However:

当我在 的第一行使用断点转到此视图控制器时-configureView,它似乎[self configureView]被调用了两次。然而:

  • Both times the method is hit, the stack looks like this:
  • 两次命中该方法时,堆栈如下所示:

stack

堆

  • When I comment [self configureView]in the above code, it's hit zero times.
  • As evident by the stack being the same both times, -configureViewdoes not call itself recursively.
  • -configureViewis only called in the above code.
  • 当我[self configureView]在上面的代码中发表评论时,它被击中了零次。
  • 正如两次相同的堆栈所证明的那样,-configureView不会递归地调用自身。
  • -configureView只在上面的代码中调用。

回答by followben

From Apple's documentation:

来自Apple 的文档

The viewWillLayoutSubviews method is also called after the view is resized and positioned by its parent.

viewWillLayoutSubviews 方法也会在视图被其父级调整大小和定位后调用。

Given viewWillLayoutSubviewsis called whenever the boundschange on the controller's view, there's no guarantee that it'll be invoked once only. It'll be called whenever rotation occurs for example.

viewWillLayoutSubviews每当bounds控制器视图发生变化时都会调用Given ,但不能保证它只会被调用一次。例如,每当发生旋转时都会调用它。

Your configureViewmethod is probably better called from somewhere else, perhaps in viewWillAppear, viewDidAppearor even a custom mutator for BirdDetailitem as per Hermann's suggestion.

根据Hermann 的建议configureView,您的方法可能最好从其他地方调用,也许在viewWillAppearviewDidAppear甚至是BirdDetailitem的自定义更改器。

回答by Hermann Klecker

If you follow the usual patterns then configureView is called in the setter of detailItem. Check the setter method. And [detailViewController setDetailItem:something]is often called in prepareForSegue:.

如果您遵循通常的模式,那么 configureView 将在detailItem. 检查 setter 方法。并且[detailViewController setDetailItem:something]经常被调用prepareForSegue:

The key point is: does it matter?

关键是:重要吗?