I have a complex view hierarchy, built in Interface Builder, with nested UIStackViews. I get "unsatisfiable constraints" notices every time I hide some of my inner stackviews. I've tracked it down to this:
(
"<NSLayoutConstraint:0x1396632d0 'UISV-canvas-connection' UIStackView:0x1392c5020.top == UILabel:0x13960cd30'Also available on iBooks'.top>",
"<NSLayoutConstraint:0x139663470 'UISV-canvas-connection' V:[UIButton:0x139554f80]-(0)-| (Names: '|':UIStackView:0x1392c5020 )>",
"<NSLayoutConstraint:0x139552350 'UISV-hiding' V:[UIStackView:0x1392c5020(0)]>",
"<NSLayoutConstraint:0x139663890 'UISV-spacing' V:[UILabel:0x13960cd30'Also available on iBooks']-(8)-[UIButton:0x139554f80]>"
)
Specifically, the UISV-spacing constraint: when hiding a UIStackView its high constraint gets a 0 constant, but that seems to clash with the inner stackview's spacing constraint: it requires 8 points between my Label and Button, which is irreconcilable with the hiding constraint and so the constraints crash.
Is there a way around this? I've tried recursively hiding all the inner StackViews of the hidden stack view, but that results in strange animations where content floats up out of the screen, and causes severe FPS drops to boot, while still not fixing the problem.
This is a known problem with hiding nested stack views.
There are essentially 3 solutions to this problem:
Change the spacing to 0, but then you'll need to remember the previous spacing value.
Call innerStackView.removeFromSuperview(), but then you'll need to remember where to insert the stack view.
Wrap the stack view in a UIView with at least one 999 constraint. E.g. top#1000, leading#1000, trailing#1000, bottom#999.
The 3rd option is the best in my opinion. For more information about this problem, why it happens, the different solutions, and how to implement solution 3, see my answer to a similar question.
So, you have this:
And the problem is, when you first collapse the inner stack, you get auto layout errors:
2017-07-02 15:40:02.377297-0500 nestedStackViews[17331:1727436] [LayoutConstraints] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(
"<NSLayoutConstraint:0x62800008ce90 'UISV-canvas-connection' UIStackView:0x7fa57a70fce0.top == UILabel:0x7fa57a70ffb0'Top Label of Inner Stack'.top (active)>",
"<NSLayoutConstraint:0x62800008cf30 'UISV-canvas-connection' V:[UILabel:0x7fa57d30def0'Bottom Label of Inner Sta...']-(0)-| (active, names: '|':UIStackView:0x7fa57a70fce0 )>",
"<NSLayoutConstraint:0x62000008bc70 'UISV-hiding' UIStackView:0x7fa57a70fce0.height == 0 (active)>",
"<NSLayoutConstraint:0x62800008cf80 'UISV-spacing' V:[UILabel:0x7fa57a70ffb0'Top Label of Inner Stack']-(8)-[UILabel:0x7fa57d30def0'Bottom Label of Inner Sta...'] (active)>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x62800008cf80 'UISV-spacing' V:[UILabel:0x7fa57a70ffb0'Top Label of Inner Stack']-(8)-[UILabel:0x7fa57d30def0'Bottom Label of Inner Sta...'] (active)>
Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
The problem, as you noted, is that the outer stack view applies a height = 0 constraint to the inner stack view. This conflicts with the 8 point padding constraint applied by the inner stack view between its own subviews. Both constraints cannot be satisfied simultaneously.
The outer stack view uses this height = 0 constraint, I believe, because it looks better when animated than just letting the inner view be hidden without shrinking first.
There's a simple fix for this: wrap the inner stack view in a plain UIView, and hide that wrapper. I'll demonstrate.
Here's the scene outline for the broken version above:
To fix the problem, select the inner stack view. From the menu bar, choose Editor > Embed In > View:
Interface Builder created a width constraint on the wrapper view when I did this, so delete that width constraint:
Next, create constraints between all four edges of the wrapper and the inner stack view:
At this point, the layout is actually correct at runtime, but Interface Builder draws it incorrectly. You can fix it by setting the vertical hugging priorities of the inner stack's children higher. I set them to 800:
We haven't actually fixed the unsatisfiable constrain problem at this point. To do so, find the bottom constraint that you just created and set its priority to less than required. Let's change it to 800:
Finally, you presumably had an outlet in your view controller connected to the inner stack view, because you were changing its hidden property. Change that outlet to connect to the wrapper view instead of the inner stack view. If your outlet's type is UIStackView, you'll need to change it to UIView. Mine was already of type UIView, so I just reconnected it in the storyboard:
Now, when you toggle the wrapper view's hidden property, the stack view will appear to collapse, with no unsatisfiable constraint warnings. It looks virtually identical, so I won't bother posting another GIF of the app running.
You can find my test project in this github repository.
I hit a similar problem with UISV-hiding. For me, the solution was to reduce the priorities of my own constraints from Required (1000) to something less than that. When UISV-hiding constrains are added, they take priority and the constraints no longer clash.
Ideally we could just set the priority of the UISV-spacing constraint to a lower value, but there doesn't appear to be any way to do that. :)
I am having success setting the spacing property of the nested stack views to 0 before hiding, and restoring to the proper value after making it visible again.
I think doing this recursively on nested stack views would work. You could store the original value of the spacing property in a dictionary and restore it later.
My project only has a single level of nesting, so I am unsure if this would result in FPS problems. As long as you don't animate the changes in spacing, I don't think it would create too much of a hit.
Another approach
Try to avoid nested UIStackViews. I love them and build almost everything with them. But as I recognized that they secretly add constraints I try to only use them at the highest level and non-nested where possible. This way I can specify the 2nd highest priority .defaultHighto the spacing constraint which resolves my warnings.
This priority is just enough to prevent most layout issues.
Of course you need to specify some more constraints but this way you have full control of them and make your view layout explicit.
Here's implementation of Senseful's suggestion #3 written as Swift 3 class using SnapKit constraints. I also tried overriding the properties, but never got it working without warnings, so I'll stick with wrapping UIStackView:
class NestableStackView: UIView {
private var actualStackView = UIStackView()
override init(frame: CGRect) {
super.init(frame: frame);
addSubview(actualStackView);
actualStackView.snp.makeConstraints { (make) in
// Lower edges priority to allow hiding when spacing > 0
make.edges.equalToSuperview().priority(999);
}
}
convenience init() {
self.init(frame: CGRect.zero);
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addArrangedSubview(_ view: UIView) {
actualStackView.addArrangedSubview(view);
}
func removeArrangedSubview(_ view: UIView) {
actualStackView.removeArrangedSubview(view);
}
var axis: UILayoutConstraintAxis {
get {
return actualStackView.axis;
}
set {
actualStackView.axis = newValue;
}
}
open var distribution: UIStackViewDistribution {
get {
return actualStackView.distribution;
}
set {
actualStackView.distribution = newValue;
}
}
var alignment: UIStackViewAlignment {
get {
return actualStackView.alignment;
}
set {
actualStackView.alignment = newValue;
}
}
var spacing: CGFloat {
get {
return actualStackView.spacing;
}
set {
actualStackView.spacing = newValue;
}
}
}
In my case I was adding width and height constraint to a navigation bar button, as per the advice above I only added lower priority to the constraints.
open func customizeNavigationBarBackButton() {
let _selector = #selector(UIViewController._backButtonPressed(_:))
let backButtonView = UIButton(type: .custom)
backButtonView.setImage(UIImage(named: "icon_back"), for: .normal)
backButtonView.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: -30, bottom: 0, right: 0)
backButtonView.snp.makeConstraints { $0.width.height.equalTo(44).priority(900) }
backButtonView.addTarget(self, action: _selector, for: .touchUpInside)
let backButton = UIBarButtonItem(customView: backButtonView)
self.navigationItem.leftBarButtonItem = backButton
}
Related
I'm trying to make this layout somehow dynamic. The options here are dynamic (unknown count), so we can easily put these options in a tableView, collectionView, or just simply scrollView.
The problem is that I wanna make this white container small if possible and centering vertically. And when I combine centerY constraint with Top+Bottom insets, only the top and bottom constraints seem to be activated.
And when the options are quite long, options can be scrollable, BUT maintaining the fact that there are top and bottom insets.
I have already some ideas in mind, such as observing if the height of the container view exceeds the device height.
I use snapKit, but the constraints should be understandable. Here's my current layout:
func setupUI() {
self.view.backgroundColor = .clear
self.view.addSubviews(
self.view_BGFilter,
self.view_Container
)
self.view_BGFilter.snp.makeConstraints {
$0.edges.equalToSuperview()
}
self.view_Container.snp.makeConstraints {
$0.centerY.equalToSuperview().priority(.high)
//$0.top.bottom.greaterThanOrEqualToSuperview().inset(80.0).priority(.medium)
$0.leading.trailing.equalToSuperview().inset(16.0)
}
// Setup container
self.view_Container.addSubviews(
self.label_Title,
self.stackView,
self.button_Submit
)
self.label_Title.snp.makeConstraints {
$0.top.equalToSuperview().inset(40.0)
$0.leading.trailing.equalToSuperview().inset(16.0)
}
self.stackView.snp.makeConstraints {
$0.top.equalTo(self.label_Title.snp.bottom).offset(29.0)
$0.leading.trailing.equalToSuperview().inset(24.0)
}
self.button_Submit.snp.makeConstraints {
$0.height.equalTo(52.0)
$0.top.equalTo(self.stackView.snp.bottom).offset(30.0)
$0.bottom.leading.trailing.equalToSuperview().inset(24.0)
}
self.generateButtons()
}
My answer your question - CenterY with Top and Bottom constraints? - comes with just a little commentary...
I know that SnapKit is popular, and I'm sure at times it can be very helpful, especially if you use it all the time.
However... when using it you can never be absolutely sure what it's doing. And, in my experience, folks who use SnapKit often don't really understand what constraints are or how they work (not implying that's the case with you ... just an observation from looking at various questions).
In this specific case, either SnapKit has a bit of a bug, or this particular line is not quite right for the desired result:
$0.top.bottom.greaterThanOrEqualToSuperview().inset(80.0)
You can confirm it with a simple test:
class TestViewController: UIViewController {
let testView: UIView = {
let v = UIView()
v.backgroundColor = .red
return v
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(testView)
testView.snp.makeConstraints {
$0.centerY.equalToSuperview()
// height exactly 200 points
$0.height.equalTo(200.0)
// top and bottom at least 80 points from superview
$0.top.bottom.greaterThanOrEqualToSuperview().inset(80.0)
$0.leading.trailing.equalToSuperview().inset(16.0)
}
}
}
This is the result... along with [LayoutConstraints] Unable to simultaneously satisfy constraints. message in debug console:
If we replace that line as follows:
// replace this line
//$0.top.bottom.greaterThanOrEqualToSuperview().inset(80.0)
// with these two lines
$0.top.greaterThanOrEqualToSuperview().offset(80.0)
$0.bottom.lessThanOrEqualToSuperview().offset(-80.0)
which certainly seems to be doing the same thing, we get what we expected:
So, something in SnapKit is fishy.
That will fix your issue. Change your view_Container constraint setup like this:
self.view_Container.snp.makeConstraints {
$0.centerY.equalToSuperview().priority(.required)
// replace this line
//$0.top.bottom.greaterThanOrEqualToSuperview().inset(80.0)
// with these two lines
$0.top.greaterThanOrEqualToSuperview().offset(80.0)
$0.bottom.lessThanOrEqualToSuperview().offset(-80.0)
$0.leading.trailing.equalToSuperview().inset(16.0)
}
Before the change:
After the change:
As to adding scrolling when you have many Option Buttons, I can give you an example for either scrolling all the content or scrolling only the Option Buttons.
I have a UIStackView defined in storyboard with the first button's height set to 70 and other one set to 45. I get this autolayout error:
[LayoutConstraints] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(
"<NSLayoutConstraint:0x280f614f0 UIButton:0x10641a120.height == 45 (active)>",
"<NSLayoutConstraint:0x280f60e60 UIButton:0x106418f80.height == 70 (active)>",
"<NSLayoutConstraint:0x280f604b0 'UISV-alignment' UIButton:0x10641a120.bottom == UIButton:0x106418f80.bottom (active)>",
"<NSLayoutConstraint:0x280f63cf0 'UISV-alignment' UIButton:0x10641a120.top == UIButton:0x106418f80.top (active)>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x280f60e60 UIButton:0x106418f80.height == 70 (active)>
I understand the UIStackView is unable to accept different heights of UIButtons, is that correct and what is the way to have UIStackView accept different heights or widths of it's elements?
Something in your Stack View constraints is causing the problem.
Here is a valid layout:
With the Stack View properties:
The result before adding a third button via code:
And the result after adding a third button (height constraint of 60) via code:
No auto-layout warnings or errors.
The code (connected to Button 1), adds / removes Button 3 as an arranged subview of the stack view:
class TestViewController: UIViewController {
#IBOutlet var theStackView: UIStackView!
var thirdButton: UIButton = {
let b = UIButton()
b.translatesAutoresizingMaskIntoConstraints = false
b.setTitle("Button 3", for: .normal)
b.backgroundColor = .red
return b
}()
#IBAction func doAddThird(_ sender: Any) {
if theStackView.arrangedSubviews.count == 2 {
theStackView.addArrangedSubview(thirdButton)
} else {
if let v = theStackView.arrangedSubviews.last {
v.removeFromSuperview()
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// finish initializing the third button
if let v = theStackView.arrangedSubviews.first as? UIButton {
thirdButton.titleLabel?.font = v.titleLabel?.font
}
NSLayoutConstraint.activate([
thirdButton.heightAnchor.constraint(equalToConstant: 60),
])
}
}
A Stackview will take on the dimensions of its components, if you don't give it height and width constraints. It looks like you are telling your stackView to be a particular height (either because you have a height constraint or two Y position constraints which imply a height). You cannot both tell the stackView to have a height and tell all of its arrangedSubviews to have a height unless those two values are exactly the same. So for instance if you tell the stack to be 150 high, and your buttons are 45 and 70 high then the one with the lowest content hugging priority loses and gets expanded to take up the extra 35 points of space that the stack view needs to be 150 points high.
Quick solutions:
Remove the hieght constraint on the stack view; it will now be as high as the sum of the high of its elements.
Add a blank UIView to the stack and give it content hugging of 1 and it will take up any extra space (this only works if your stack is bigger than its elements; if its too small you need to reduce the size of the arrangedSubviews instead).
My original ViewController consists of only one scrollView like this:
Now I also have my own xib file (CheckBoxView) which mainly consists of one button, see this screenshot:
I dynamically create some UIStackViews and add them to the ScrollView Inside these UIStackViews I add multiple instances of my xib file.
What I want to achieve is, that the StackViews are just vertically stacked. And inside the StackViews the UIViews from my xib-file should also be vertically stacked.
At the moment it looks like this:
So the xib-Views are not in the whole view. Since I am using multi-os-engine I can't provide swift/obj-c code. But here is my Java-Code:
for (ItemConfiguration config : itemInstance.getConfigurations()) {
List<DLRadioButton> radioButtons = new ArrayList<DLRadioButton>();
UIStackView configView = UIStackView.alloc().initWithFrame(new CGRect(new CGPoint(0, barHeight), new CGSize(displayWidth, displayHeight - barHeight)));
configView.setAxis(UILayoutConstraintAxis.Vertical);
configView.setDistribution(UIStackViewDistribution.EqualSpacing);
configView.setAlignment(UIStackViewAlignment.Center);
configView.setSpacing(30);
for (ConfigurationOption option : config.getOptions()) {
UIView checkBox = instantiateFromNib("CheckBoxView");
for (UIView v : checkBox.subviews()) {
if (v instanceof DLRadioButton) {
((DLRadioButton) v).setTitleForState(option.getName(), UIControlState.Normal);
//((DLRadioButton) v).setIconSquare(true);
radioButtons.add((DLRadioButton) v);
}
}
configView.addArrangedSubview(checkBox);
}
// group radiobuttons
//groupRadioButtons(radioButtons);
configView.setTranslatesAutoresizingMaskIntoConstraints(false);
scrollView().addSubview(configView);
configView.centerXAnchor().constraintEqualToAnchor(scrollView().centerXAnchor()).setActive(true);
configView.centerYAnchor().constraintEqualToAnchor(scrollView().centerYAnchor()).setActive(true);
}
private UIView instantiateFromNib(String name) {
return (UIView) UINib.nibWithNibNameBundle(name, null).instantiateWithOwnerOptions(null, null).firstObject();
}
How do I need to set the Alignments etc. to Achieve what I want. It should look like this:
I don't know if there is a reason to not use UITableView, that i highly recommend for your case. In case it's not possible, below you can find some pieces of advice that should help.
If you use Auto Layout, you should set constraints for all views instantiated in your code. The constraints must be comprehensive for iOS to know each view's position and size.
Remove redundant constraints
configView.centerXAnchor().constraintEqualToAnchor(scrollView().centerXAnchor()).setActive(true);
configView.centerYAnchor().constraintEqualToAnchor(scrollView().centerYAnchor()).setActive(true);
These two constraint just doesn't make sense to me. You need the stackviews be stacked within you ScrollView, but not centered. If i understand you goal correctly, this should be removed
Set width/x-position constraints for UIStackViews
configView.setTranslatesAutoresizingMaskIntoConstraints(false);
scrollView().addSubview(configView);
Right after a stack view is added to the ScrollView, you need to set up constraints for it. I'll provide my code in swift, but it looks quite similar to what your Java code is doing, so hopefully you'll be able to transpile it without difficulties:
NSLayoutConstraint.activate([
configView.leadingAnchor.constraintEqualToAnchor(scrollView.leadingAnchor),
configView.trailingAnchor.constraintEqualToAnchor(scrollView.trailingAnchor)
]);
Set height constraints for UIStackViews
StackViews doesn't change their size whenever you add arranged view in it. So you need to calculate a desired stackview size yourself and specify it explicitly via constraints. It should be enough to accommodate items and spaces between them. I suppose that all items should be of the same size, let it be 32 points, then height should be:
let stackViewHeight = items.count * 32 + stackView.space * (items.count + 1)
And make new height constraint for the stack view:
configView.heightAnchor.constraint(equalToConstant: stackViewHeight).isActive = true
Set y-position for UIStackView
This is a little bit more challenging part, but the most important for the views to work properly in a scroll view.
1) Change loop to know the index of a UIStackView
A scroll view should always be aware of height of its content, so you need to understand which stack view is the top one, and which is the bottom. In order to do that, you need to change for each loop to be written as for(;;) loop:
for (int i = 0; i < itemInstance.getConfigurations().length; i++) {
ItemConfiguration config = itemInstance.getConfigurations()[i]
...
}
I'm not aware of which type your array is, so if it doesn't have subscript functionality, just replace it with corresponding method.
2) Set top anchor for stack views
For the first stack view in the array, top anchor should be equal to the scroll view top anchor, for others it should be bottom anchor of the previous stack view + spacing between them (say, 8 points in this example):
if i == 0 {
configView.topAnchor.constraintEqualToAnchor(scrollView.topAnchor, constant: 8).isActive = true
} else {
let previousConfigView = itemInstance.getConfigurations()[i - 1]
configView.topAnchor.constraintEqualToAnchor(previousConfigView.bottomAnchor, constant: 8).isActive = true
}
3) Set bottom anchor for the last stack view
As was said - for the Scroll View to be aware of content size, we need to specify corresponding constraints:
if i == itemInstance.getConfigurations() - 1 {
configView.bottomAnchor.constraintEqualToAnchor(scrollView.bottomAnchor, constant: 8).isActive = true
}
Note: please be advised, that all constraints should be set on views that are already added to the scroll view.
I've had a very frustrating time working with constraints programatically in Swift 3. At a very basic level, my application displays a number of views with initial constraints, and then applies new constraints upon rotation, to allow the views to resize and reposition as needed. Unfortunately this has been far from easy as I am still new to iOS development and Swift. I've spent a lot of time trying many different solutions offered on StackOverflow and elsewhere, but I keep reaching the same outcome (detailed at the end).
I have a view controller (let's call it "Main View Controller") whose root view contains two subviews, View A and View B Container. The root view has a pink background color.
View A contains a single label inside, centered vertically and horizontally, as well as an orange background color. View A has 4 constraints - [Leading Space to Superview], [Top Space to Top Layout Guide], [Trailing Space to Superview] and [Bottom Space to Bottom Layout Guide].
View B Container initially has no content. It has 4 constraints - [Width Equals 240], [Height Equals 128], [Leading Space to Superview] and [Leading Space to Superview].
I also have another view controller (let's call it "View B View Controller") that drives the content for the View B Container. For the sake of simplicity, this is just a default view controller with no custom logic. The root view of View B View Controller contains a single subview, View B.
View B is almost identical to View A above - single label centered vertically and horizontally and a blue background color. View B has 4 constraints - [Leading Space to Superview], [Top Space to Superview], [Trailing Space to Superview] and [Bottom Space to Superview].
In the Main View Controller class, I've maintained IBOutlet references to View A and View B Container, as well as their respective constraints mentioned above. In the below code, the Main View Controller instantiates the View B View Controller and adds the subsequent view to the View B Container, applying a flexible width/height auto-resizing mask to ensure it fills the available space. Then it fires a call to the internal _layoutContainers() function which performs a number of constraint-modifying operations depending on the device's orientation. The current implementation does the following:
removes the known constraints from View A
removes the known constraints from View B Container
depending on device orientation, activate new constraints for both View A and View B Container according to a specific design (detailed in code comments below)
fire off updateConstraintsIfNeeded() and layoutIfNeeded() against all views
When a resize event occurs, the code allows the viewWillTransition() to fire and then calls the _layoutContainers() function in the completion callback, so that the device is in a new state and can follow the necessary logic path.
The entire Main View Controller unit is below:
import UIKit
class ViewController: UIViewController {
// MARK: Variables
#IBOutlet weak var _viewAView: UIView!
#IBOutlet weak var _viewALeadingConstraint: NSLayoutConstraint!
#IBOutlet weak var _viewATopConstraint: NSLayoutConstraint!
#IBOutlet weak var _viewATrailingConstraint: NSLayoutConstraint!
#IBOutlet weak var _viewABottomConstraint: NSLayoutConstraint!
#IBOutlet weak var _viewBContainerView: UIView!
#IBOutlet weak var _viewBContainerWidthConstraint: NSLayoutConstraint!
#IBOutlet weak var _viewBContainerHeightConstraint: NSLayoutConstraint!
#IBOutlet weak var _viewBContainerTopConstraint: NSLayoutConstraint!
#IBOutlet weak var _viewBContainerLeadingConstraint: NSLayoutConstraint!
// MARK: UIViewController Overrides
override func viewDidLoad() {
super.viewDidLoad()
// Instantiate View B's controller
let viewBViewController = self.storyboard!.instantiateViewController(withIdentifier: "ViewBViewController")
self.addChildViewController(viewBViewController)
// Instantiate and add View B's new subview
let view = viewBViewController.view
self._viewBContainerView.addSubview(view!)
view!.frame = self._viewBContainerView.bounds
view!.autoresizingMask = [.flexibleWidth, .flexibleHeight]
viewBViewController.didMove(toParentViewController: self)
self._layoutContainers()
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: nil, completion: { _ in
self._layoutContainers()
})
}
// MARK: Internal
private func _layoutContainers() {
// Remove View A constraints
self._viewAView.removeConstraints([
self._viewALeadingConstraint,
self._viewATopConstraint,
self._viewATrailingConstraint,
self._viewABottomConstraint,
])
// Remove View B Container constraints
var viewBContainerConstraints: [NSLayoutConstraint] = [
self._viewBContainerTopConstraint,
self._viewBContainerLeadingConstraint,
]
if(self._viewBContainerWidthConstraint != nil) {
viewBContainerConstraints.append(self._viewBContainerWidthConstraint)
}
if(self._viewBContainerHeightConstraint != nil) {
viewBContainerConstraints.append(self._viewBContainerHeightConstraint)
}
self._viewBContainerView.removeConstraints(viewBContainerConstraints)
// Portrait:
// View B - 16/9 and to bottom of screen
// View A - anchored to top and filling the remainder of the vertical space
if(UIDevice.current.orientation != .landscapeLeft && UIDevice.current.orientation != .landscapeRight) {
let viewBWidth = self.view.frame.width
let viewBHeight = viewBWidth / (16/9)
let viewAHeight = self.view.frame.height - viewBHeight
// View A - anchored to top and filling the remainder of the vertical space
NSLayoutConstraint.activate([
self._viewAView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
self._viewAView.topAnchor.constraint(equalTo: self.view.topAnchor),
self._viewAView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
self._viewAView.bottomAnchor.constraint(equalTo: self._viewBContainerView.topAnchor),
])
// View B - 16/9 and to bottom of screen
NSLayoutConstraint.activate([
self._viewBContainerView.widthAnchor.constraint(equalToConstant: viewBWidth),
self._viewBContainerView.heightAnchor.constraint(equalToConstant: viewBHeight),
self._viewBContainerView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: viewAHeight),
self._viewBContainerView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
])
}
// Landscape:
// View B - 2/3 of screen on left
// View A - 1/3 of screen on right
else {
let viewBWidth = self.view.frame.width * (2/3)
// View B - 2/3 of screen on left
NSLayoutConstraint.activate([
self._viewBContainerView.widthAnchor.constraint(equalToConstant: viewBWidth),
self._viewBContainerView.heightAnchor.constraint(equalToConstant: self.view.frame.height),
self._viewBContainerView.topAnchor.constraint(equalTo: self.view.topAnchor),
self._viewBContainerView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
])
// View A - 1/3 of screen on right
NSLayoutConstraint.activate([
self._viewAView.leadingAnchor.constraint(equalTo: self._viewBContainerView.trailingAnchor),
self._viewAView.topAnchor.constraint(equalTo: self.view.topAnchor),
self._viewAView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
self._viewAView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor)
])
}
// Fire off constraints and layout update functions
self.view.updateConstraintsIfNeeded()
self._viewAView.updateConstraintsIfNeeded()
self._viewBContainerView.updateConstraintsIfNeeded()
self.view.layoutIfNeeded()
self._viewAView.layoutIfNeeded()
self._viewBContainerView.layoutIfNeeded()
}
}
My problem is that, although the initial load of the application displays the expected result (View B maintaining a 16/9 ratio and sitting at the bottom of the screen, View A taking up the remaining space):
Any subsequent rotation breaks the views completely and doesn't recover:
Additionally, the following constraints warnings are thrown once the application loads:
TestResize[1794:51030] [LayoutConstraints] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(
"<_UILayoutSupportConstraint:0x600000096c60 _UILayoutGuide:0x7f8d4f414110.height == 0 (active)>",
"<_UILayoutSupportConstraint:0x600000090ae0 V:|-(0)-[_UILayoutGuide:0x7f8d4f414110] (active, names: '|':UIView:0x7f8d4f40f9e0 )>",
"<NSLayoutConstraint:0x600000096990 V:[_UILayoutGuide:0x7f8d4f414110]-(0)-[UIView:0x7f8d4f413e60] (active)>",
"<NSLayoutConstraint:0x608000094e10 V:|-(456.062)-[UIView:0x7f8d4f413e60] (active, names: '|':UIView:0x7f8d4f40f9e0 )>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x600000096990 V:[_UILayoutGuide:0x7f8d4f414110]-(0)-[UIView:0x7f8d4f413e60] (active)>
Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
TestResize[1794:51030] [LayoutConstraints] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(
"<NSLayoutConstraint:0x600000096940 UIView:0x7f8d4f413e60.leading == UIView:0x7f8d4f40f9e0.leadingMargin (active)>",
"<NSLayoutConstraint:0x608000094e60 H:|-(0)-[UIView:0x7f8d4f413e60] (active, names: '|':UIView:0x7f8d4f40f9e0 )>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x600000096940 UIView:0x7f8d4f413e60.leading == UIView:0x7f8d4f40f9e0.leadingMargin (active)>
Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
TestResize[1794:51030] [LayoutConstraints] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(
"<_UILayoutSupportConstraint:0x600000096d50 _UILayoutGuide:0x7f8d4f40f4b0.height == 0 (active)>",
"<_UILayoutSupportConstraint:0x600000096d00 _UILayoutGuide:0x7f8d4f40f4b0.bottom == UIView:0x7f8d4f40f9e0.bottom (active)>",
"<NSLayoutConstraint:0x600000092e30 V:[UIView:0x7f8d4f40fd90]-(0)-[_UILayoutGuide:0x7f8d4f40f4b0] (active)>",
"<NSLayoutConstraint:0x608000092070 UIView:0x7f8d4f40fd90.bottom == UIView:0x7f8d4f413e60.top (active)>",
"<NSLayoutConstraint:0x608000094e10 V:|-(456.062)-[UIView:0x7f8d4f413e60] (active, names: '|':UIView:0x7f8d4f40f9e0 )>",
"<NSLayoutConstraint:0x600000096e40 'UIView-Encapsulated-Layout-Height' UIView:0x7f8d4f40f9e0.height == 667 (active)>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x600000092e30 V:[UIView:0x7f8d4f40fd90]-(0)-[_UILayoutGuide:0x7f8d4f40f4b0] (active)>
Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
TestResize[1794:51030] [LayoutConstraints] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(
"<_UILayoutSupportConstraint:0x600000096c60 _UILayoutGuide:0x7f8d4f414110.height == 20 (active)>",
"<_UILayoutSupportConstraint:0x600000090ae0 V:|-(0)-[_UILayoutGuide:0x7f8d4f414110] (active, names: '|':UIView:0x7f8d4f40f9e0 )>",
"<NSLayoutConstraint:0x600000096850 V:[_UILayoutGuide:0x7f8d4f414110]-(0)-[UIView:0x7f8d4f40fd90] (active)>",
"<NSLayoutConstraint:0x608000093b50 V:|-(0)-[UIView:0x7f8d4f40fd90] (active, names: '|':UIView:0x7f8d4f40f9e0 )>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x600000096850 V:[_UILayoutGuide:0x7f8d4f414110]-(0)-[UIView:0x7f8d4f40fd90] (active)>
Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
Thank you for reading if you got this far! Surely someone has encountered (and hopefully solved) this or a similar issue. Any help would be immensely appreciated!
Instead of trying to add and remove constraints consider just adjusting a priority to transform your view instead.
So for you default layout have a constraint with priority 900. Then add a second conflicting constraint with priority 1. Now to toggle the display mode just move that second constraint priority up above 900, and then back below to reverse. Easy to test it all in Interface Builder by just changing the priority too.
Also you can put the change in an animation block to get a nice smooth transition.
-
One other thing to consider using is size classes. Using this you can specify that particular constraints only apply for certain orientations so you could probably get your desired behaviour entirely 'for free', just set it all up in IB.
Part of the issue is that in _layoutContainers you remove the constaints from the storyboard and add now ones, but on subsequent rotations you don't remove the previous ones you added. You should store the new constraints that you create so that the next time the screen rotates, you can get the old constraints and remove them.
Also, calling _layoutContainers from viewDidLoad is too early in the VCs lifecycle since the views frame won't have the correct value yet. You can crate aspect ratio constraints so you don't have to calculate the size manually.
For example, the portrait constraint for
// View B - 16/9 and to bottom of screen
NSLayoutConstraint.activate([
self._viewBContainerView.heightAnchor.constraint(equalToConstant: self._viewBContainerView.widthAnchor, multiplier: 16.0 / 9.0),
self._viewBContainerView.topAnchor.constraint(equalTo: self.view.bottomAnchor),
self._viewBContainerView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
// should there be a constraint for self._viewBContainerView.trailingAnchor?
])
I'm trying to programmatically modify autolayout constraints to move a table view up, but only for an iPhone 6 Plus in landscape mode, because I couldn't achieve the precise visual effect I wanted on all devices using Xcode 6.2 beta 3 Interface Builder's autolayout (got it right from IB for the other supported devices/orientations. Just that iPhone 6 Plus is a bit of an outlier between an iPhone and an iPad, thus a little trickier)
One constraint I remove seems to be deleted after removal (e.g. disappears from the containing view's constraints, as expected), however, the layout manager still seems to finds it and warns that it is a conflict with other constraints and breaks a constraint at runtime with the fortunate result that the app produces the intended visual result, but the unfortunate side-effect of an ugly console warning message, that I want to fix, because it's ugly and Apple documentation blames such warnings user code bug(s).
My code intercepts orientation change (only on iPhone 6 Plus),
and then:
=============
• Iterates over constraints in tableview's owner view
• Prints properties of any constraint with an attribute of .Top
• Removes Center Y constraint referenced via IBOutlet, for the tableview
• Removes constraint with .Top attribute
• Adds new .Top attribute with a different multiplier
============
Here is the swift code in my View Controller:
override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
switch(toInterfaceOrientation) {
case .LandscapeLeft:
fallthrough
case .LandscapeRight:
var deviceType = UIDevice().deviceType
if (deviceType == .iPhone6plus || deviceType == .simulator) {
if centerYconstraint != nil {
self.view.removeConstraint(centerYconstraint)
centerYconstraint = nil
for constraint in self.view.constraints() {
if (constraint.firstItem as NSObject == self.tableView) {
if (constraint.firstAttribute == NSLayoutAttribute.Top) {
println("found item \(constraint)")
let view1 = constraint.firstItem as UIView
let attr1 = constraint.firstAttribute
let view2 = constraint.secondItem as UIView
let attr2 = constraint.secondAttribute
let relation = constraint.relation
let constant = constraint.constant
let newConstraint = NSLayoutConstraint(
item: view1,
attribute: attr1,
relatedBy: relation,
toItem: view2,
attribute: attr2,
multiplier: 0.02,
constant: constant)
self.view.removeConstraint(constraint as NSLayoutConstraint)
self.view.addConstraint(newConstraint)
self.view.layoutIfNeeded()
}
}
}
}
}
default:
break
}
}
Here is Xcode simulator's output. Notice the first line "found item" where I print the constraint I delete.
But you can see the same view1 and view2, multiplier and attribute in the list of potential contflicts layout manager complains about afterward. That's what I'm confused about.
found item <NSLayoutConstraint:0x7f8a05101bb0 UITableView:0x7f8a05853000.top == 0.03*_UILayoutGuide:0x7f8a035517e0.top>
2015-01-03 14:36:35.290 Interphase[46388:74323123] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
"<NSLayoutConstraint:0x7f8a0354da40 V:[UITableView:0x7f8a05853000(336)]>",
"<_UILayoutSupportConstraint:0x7f8a0514df70 V:[_UILayoutGuide:0x7f8a035517e0(49)]>",
"<_UILayoutSupportConstraint:0x7f8a051908e0 _UILayoutGuide:0x7f8a035517e0.bottom == UIView:0x7f8a03551480.bottom>",
"<NSLayoutConstraint:0x7f8a051b53d0 'UIView-Encapsulated-Layout-Height' V:[UIView:0x7f8a03551480(414)]>",
"<NSLayoutConstraint:0x7f8a050d9080 UITableView:0x7f8a05853000.top == 0.02*_UILayoutGuide:0x7f8a035517e0.top>",
"<NSLayoutConstraint:0x7f8a0354ef80 UITableView:0x7f8a05853000.centerY == UIView:0x7f8a03551480.centerY>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x7f8a0354da40 V:[UITableView:0x7f8a05853000(336)]>
Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
2015-01-03 14:36:56.720 Interphase[46388:74323123] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
"<_UILayoutSupportConstraint:0x7f8a0514df70 V:[_UILayoutGuide:0x7f8a035517e0(49)]>",
"<_UILayoutSupportConstraint:0x7f8a051908e0 _UILayoutGuide:0x7f8a035517e0.bottom == UIView:0x7f8a03551480.bottom>",
"<NSLayoutConstraint:0x7f8a05101bb0 UITableView:0x7f8a05853000.top == 0.03*_UILayoutGuide:0x7f8a035517e0.top>",
"<NSLayoutConstraint:0x7f8a051b53d0 'UIView-Encapsulated-Layout-Height' V:[UIView:0x7f8a03551480(736)]>",
"<NSLayoutConstraint:0x7f8a050d9080 UITableView:0x7f8a05853000.top == 0.02*_UILayoutGuide:0x7f8a035517e0.top>"
)
Adding and removing constraints to a view is a bit flaky. It's never entirely clear which view they should be added to and then it makes it hard to find later when you want to remove it.
A better solution is to keep a reference to the constraint(s) you care about (either as outlets if you're doing it from interface builder, or just store them in properties) and then activate or deactivate them as required.
Activating constraints instead of adding them also prevents you having to decide which is the appropriate view to add them to - the system does this automatically.