我以编程方式将childVC(DrawerViewController)内置到mainVC(HomeController)中,现在我需要topAnchor参考。
我知道我可以使用IBOutlets引用单个约束并将其命名,但是我想学习如何以编程方式构建没有Storyboard的东西。现在,我很难解决如何以编程方式正确引用我的子容器的topAnchor来进一步处理此变量的问题。
作为IBO,它会像这样完美地工作:
@IBOutlet private var containerViewTopConstraint: NSLayoutConstraint!
因此,我需要以编程方式引用我的topAnchor,并将其命名为containerViewTopConstraint。以编程方式嵌入childVC的代码:
let drawerViewController = DrawerViewController()
func addDrawer() {
addChild(drawerViewController)
view.addSubview(drawerViewController.view)
drawerViewController.didMove(toParent: self)
addDrawerConstraints()
}
func addDrawerConstraints() {
drawerViewController.view.translatesAutoresizingMaskIntoConstraints = false
drawerViewController.view.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20).isActive = true
drawerViewController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
drawerViewController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true
drawerViewController.view.heightAnchor.constraint(equalToConstant: UIScreen.main.bounds.height).isActive = true
}
override func viewDidLoad() {
super.viewDidLoad()
addDrawer()
}
这是我的操作方式。它涉及两件事。首先,设置always相同的约束,设置为isActive = true
。然后,对于一个(或多个),根据需要激活/停用:
let drawer = UIView()
var drawerOut = [NSLayoutConstraint]()
var drawerIn = [NSLayoutConstraint]()
// place in viewDidLoad()
drawer.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
drawer.widthAnchor.constraint(equalToConstant: 526).isActive = true
drawer.heightAnchor.constraint(equalToConstant: 374).isActive = true
drawerIn.append(drawer.topAnchor.constraint(equalTo: view.bottomAnchor, constant: 526))
drawerOut.append(drawer.topAnchor.constraint(equalTo: safeAreaView.bottomAnchor, constant: -370))
NSLayoutConstraint.activate(drawerIn)
// functions to open/close drawer
func openDrawer() {
NSLayoutConstraint.deactivate(drawerIn)
NSLayoutConstraint.activate(drawerOut)
UIView.animate(withDuration: 0.3) { self.view.layoutIfNeeded() }
}
func closeDrawer() {
NSLayoutConstraint.deactivate(drawerOut)
NSLayoutConstraint.activate(drawerIn)
UIView.animate(withDuration: 0.3) { self.view.layoutIfNeeded() }
}
UIView.animate(withDuration:)
为所有内容添加了漂亮的动画。