UIViewController 的视图没有被 viewWillAppear() 调整大小 [英] UIViewController's view not resized by viewWillAppear()

查看:23
本文介绍了UIViewController 的视图没有被 viewWillAppear() 调整大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用自定义视图控制器实例化了一个 UINavigationController.它的视图包含一个按钮,当点击该按钮时,导航控制器会将不同的自定义视图控制器的视图推送到视图中:

I have instantiated a UINavigationController with a custom view controller. Its view contains a button that, when tapped, will have the navigation controller push the view of a different custom view controller into view:

@IBAction func showVC(sender: AnyObject) {
    let vc = MyOtherViewController()
    navigationController?.pushViewController(vc, animated: true)
}

MyOtherViewController 的 viewWillAppear() 函数中,我看到视图没有调整大小以适应视图层次结构.

In MyOtherViewController's viewWillAppear() function, I see that the view has not be resized to fit in the view hierarchy.

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    print("view: \(view)")
}

print() 函数的输出是:

视图:<UIView:0x7f9432719bd0;框架 = (0 0; 600 600);自动调整大小 = W+H;层 = <CALayer: 0x7f9432717cc0>>

view: <UIView: 0x7f9432719bd0; frame = (0 0; 600 600); autoresize = W+H; layer = <CALayer: 0x7f9432717cc0>>

如您所见,此时视图的大小仍为 600 x 600,这是 .xib 文件中的原始大小.我没有在 .xib 中调整视图的大小,因为视图将显示在各种 iPhone 和 iPad 显示器上.

As you can see, the size of the view is still 600 x 600 at this point, which is the original size from the .xib file. I haven't adjusted the size of the view in the .xib because the view will be shown on various iPhone and iPad displays.

我的困境是我需要视图的最终尺寸,因为我需要根据视图的宽度构造一些 NSLayoutConstraints.

My dilemma is that I need the final dimensions of the view as I need to construct some NSLayoutConstraints based on the width of the view.

调整视图大小的推荐方法是什么?期望在调用 -viewWillAppear() 时调整视图大小是否错误?

What is the recommended approach for having the view resized? Is it wrong to expect the view to be resized by the time -viewWillAppear() is invoked?

推荐答案

期望在调用 -viewWillAppear() 时调整视图大小是错误的吗?

Is it wrong to expect the view to be resized by the time -viewWillAppear() is invoked?

是的.您可以确定它会在 viewDidAppear 时调整大小.但这对于您的目的来说可能为时已晚.正在寻找的事件可能是viewWillLayoutSubviewsviewDidLayoutSubviews.以后会调用很多次,所以如果你想此时只执行一次修改,使用布尔标志:

Yes. You can be certain that it will be resized by the time viewDidAppear. But that might be too late for your purposes. The event you are looking for is probably viewWillLayoutSubviews or viewDidLayoutSubviews. This will be called many times in the future, so if you want to perform modifications only once at this time, use a boolean flag:

var didSetUp = false
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    if self.didSetUp { return }
    self.didSetUp = true
    // ... do stuff ...
}

这篇关于UIViewController 的视图没有被 viewWillAppear() 调整大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆