提问人:Bob de Graaf 提问时间:8/29/2023 最后编辑:Bob de Graaf 更新时间:8/30/2023 访问量:57
UIViewController addChild 和 translatesAutoresizingMaskIntoConstraints
UIViewController addChild and translatesAutoresizingMaskIntoConstraints
问:
在使用 addChild 时,我看到一些关于 translatesAutoresizingMaskIntoConstraints 的奇怪行为。
我以编程方式创建了一个 UITableViewController,将其放入 UINavigationController 中,也是以编程方式创建的,因此不涉及情节提要或类似内容。然后,当我小时候添加导航控制器时,一切都很完美。请看我使用的代码:
//Add Child View Controller
self.addChild(viewController)
//Add Child View as Subview
self.view.addSubview(viewController.view)
print("TranslatesAutoresizingMaskIntoConstraints: \(viewController.view.translatesAutoresizingMaskIntoConstraints)")
//Define Constraints
NSLayoutConstraint.activate([
viewController.view.topAnchor.constraint(equalTo: self.view.topAnchor),
viewController.view.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
viewController.view.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
viewController.view.trailingAnchor.constraint(equalTo: self.view.trailingAnchor)
])
//Notify Child View Controller
viewController.didMove(toParent: self)
然后我发现我实际上不需要 navigationController,所以我只是将我的 tableviewcontroller 本身添加为孩子。突然,它不再起作用了,我看到了一个空屏幕。我打印出框架,它是 0,0,0,0。 然后,我想起当我使用'NSLayoutConstraint.activate'时,我需要将'translatesAutoresizingMaskIntoConstraints'设置为false。
所以我做到了,而且,正如我所期望的那样,它又起作用了。但这对我来说很奇怪,因为据我所知,UINavigationControllers 并没有自动将 translatesAutoresizingMaskIntoConstraints 设置为 false。因此,我将其放回导航控制器中并打印出 translatesAutoresizingMaskIntoConstraints 的值,令我惊讶的是,显示的值显示它已设置为 true!但不知何故,它仍然有效,我完美地看到了 tableviewcontroller!
我还在 viewDidAppear 和其他地方打印了 translatesAutoresizingMaskIntoConstraints 的值,但打印的值在任何地方都是真实的。 UINavigationController 会在某个地方神奇地做一些事情吗?
答: 暂无答案
评论
translatesAutoresizingMaskIntoConstraints
translatesAutoresizingMaskIntoConstraints