Reputation: 83
I saw several questions related to this issue, but no answers applicable to my case.
I have a view controller (sampleVC) inside a container (sampleContainer) that loads perfectly in whichever position you start with, but that won't resize after changing from landscape to portrait or vice-versa.
In my view controller I have:
func addSampleVC() {
self.addChild(self.sampleVC)
self.sampleVC.didMove(toParent: self)
self.sampleContainer.addSubview(self.sampleVC.view)
self.addSampleConstraints()
}
func addSampleConstraints() {
sampleContainer.bounds = CGRect(x: 0, y: -20, width: sampleContainer.bounds.width, height: sampleContainer.bounds.height)
sampleVC.view.bounds = CGRect(x: 0, y: 0, width: sampleContainer.bounds.width * 0.94, height: sampleContainer.bounds.height)
sampleVC.view.leftAnchor.constraint(equalTo: sampleContainer.leftAnchor, constant: 20).isActive = true
sampleContainer.clipsToBounds = true
NSLayoutConstraint.constrain(view: sampleVC.view, containerView: sampleContainer)
}
The function addSampleVC is called from viewDidLoad. Based on other answers, I tried getting the updated container bounds inside viewWillTransition and then calling setNeedsLayout and setNeedsUpdate, but I must be missing something, because nothing seems to work. Thanks for any ideas.
Upvotes: 0
Views: 1219
Reputation: 1630
I have dealt once with view containers, so I'll try to help you as best I can.
You can choose to use auto-layout or "manual" layout (aka auto resizing constraints). In your code, inside the addSampleConstraints, the left anchor statement in line 3 will be ignored since auto layout was not explicitly set.
func addSampleVC() {
self.addChild(self.sampleVC)
self.sampleContainer.addSubview(self.sampleVC.view)
self.addSampleConstraints()
self.sampleVC.didMove(toParent: self)
}
func addSampleConstraints() {
sampleContainer.bounds = CGRect(x: 0, y: -20, width: sampleContainer.bounds.width, height: sampleContainer.bounds.height)
sampleVC.view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
sampleVC.view.frame = CGRect(x: 0, y: 0, width: sampleContainer.bounds.width * 0.94, height: sampleContainer.bounds.height)
sampleContainer.clipsToBounds = true
}
func addSampleConstraints() {
sampleContainer.translatesAutoResizingMaskIntoConstraints = false // Setting Auto layout
sampleVC.view.translatesAutoResizingMaskIntoConstraints = false // Setting Auto layout
sampleVC.view.topAnchor.constraint(equalTo: sampleContainer.topAnchor).isActive = true
sampleVC.view.bottomAnchor.constraint(equalTo: sampleContainer.bottomAnchor).isActive = true
sampleVC.view.widthAnchor.constraint(equalTo: sampleContainer.widthAnchor, multiplier: 0.94).isActive = true
sampleVC.view.leftAnchor.constraint(equalTo: sampleContainer.leftAnchor, constant: 20).isActive = true
sampleContainer.clipsToBounds = true
}
Upvotes: 1