isMovingToParentViewController

isMovingToParentViewController

我有一个viewController,我使用的是定位点,我想获取按钮的框架。我只在按下视图时才需要框架,所以我使用isMovingToParentViewController。像这样:

if isMovingToParentViewController {

    let myButtonFrame = myButton.convert(myButton.bounds, to: self.view)
}


当我将其添加到viewWillAppear时,用于获取按钮框架的代码将运行,但是当我将相同的代码添加至viewDidLayoutSubviews时,它将无法运行。

这是为什么?

只是要在viewDidLayoutSubviews中明确说明,当我添加断点时,它确实会命中if isMovingToParentViewController,但其中的代码永远不会命中。

当视图被推入时,isMovingToParentViewController确实被命中,当它弹出时,isMovingToParentViewController未被命中。

override func viewDidLoad() {
    super.viewDidLoad()

    // anchors are set here but the frames haven't been set yet
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    if isMovingToParentViewController {

        // this code runs
        let myButtonFrame = myButton.convert(myButton.bounds, to: self.view)
    }
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    if isMovingToParentViewController {

        // this code NEVER runs
        let myButtonFrame = myButton.convert(myButton.bounds, to: self.view)
    }
}

最佳答案

标头文档指出isMovingToParentViewController和其他3种方法仅在外观回调(例如viewWillAppear)中有效,因此在布局回调(例如viewDidLayoutSubviews)中无效。

/*
  These four methods can be used in a view controller's appearance callbacks to determine if it is being
  presented, dismissed, or added or removed as a child view controller. For example, a view controller can
  check if it is disappearing because it was dismissed or popped by asking itself in its viewWillDisappear:
  method by checking the expression ([self isBeingDismissed] || [self isMovingFromParentViewController]).
*/

#if UIKIT_DEFINE_AS_PROPERTIES
@property(nonatomic, readonly, getter=isBeingPresented) BOOL beingPresented NS_AVAILABLE_IOS(5_0);
@property(nonatomic, readonly, getter=isBeingDismissed) BOOL beingDismissed NS_AVAILABLE_IOS(5_0);

@property(nonatomic, readonly, getter=isMovingToParentViewController) BOOL movingToParentViewController NS_AVAILABLE_IOS(5_0);
@property(nonatomic, readonly, getter=isMovingFromParentViewController) BOOL movingFromParentViewController NS_AVAILABLE_IOS(5_0);
#else
- (BOOL)isBeingPresented NS_AVAILABLE_IOS(5_0);
- (BOOL)isBeingDismissed NS_AVAILABLE_IOS(5_0);

- (BOOL)isMovingToParentViewController NS_AVAILABLE_IOS(5_0);
- (BOOL)isMovingFromParentViewController NS_AVAILABLE_IOS(5_0);
#endif

10-05 20:29