此应用没有故事板。这是实例化ViewController2
(page2
)的根视图控制器。 ViewController2
的视图被赋予约束(前导,顶部,宽度,高度)。除非在UINavigationController
中创建page2
,否则约束似乎效果很好。
class ViewController0: UIViewController {
let scrollView = UIScrollView()
let page1 = ViewController1()
let page2 = ViewController2()
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.allButUpsideDown
}
override func loadView() {
setView()
addScrollView()
addToScrollView()
}
func setView() {
view = UIView()
}
func addScrollView() {
scrollView.bounces = false
scrollView.isPagingEnabled = true
scrollView.backgroundColor = UIColor.brown
scrollView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(scrollView)
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
scrollView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1.0).isActive = true
scrollView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 1.0).isActive = true
}
func addToScrollView() {
addChildViewController(page1)
page1.view.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(page1.view)
page1.didMove(toParentViewController: self)
page1.view.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
page1.view.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
page1.view.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1.0).isActive = true
page1.view.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 1.0).isActive = true
page1.view.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
addChildViewController(page2)
page2.view.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(page2.view)
page2.didMove(toParentViewController: self)
page2.view.leadingAnchor.constraint(equalTo: page1.view.trailingAnchor).isActive = true
page2.view.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
page2.view.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1.0).isActive = true
page2.view.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 1.0).isActive = true
page2.view.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
page2.view.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
}
}
由于导航控制器在page2
上正常工作,我必须明确设置视图的框架,如下所示view.frame = UIScreen.main.bounds
,即使我在{{}设置了它1}}使用约束。如果我不再设置视图的框架(如下),则视图的边界会扩展到无穷大,ViewController0
内的约束变得无用。
page2
我的印象是,当你使用约束时,你可以完全放弃视图的frame属性。我没有正确设置约束吗?或者因为这纯粹是程序化的,所以我有时必须明确设置视图的框架?