Constraint changes of super view not reflecting in sub views - ios

Objective:
I have 4 views arranged one below the other. The views also consists of subViews. Suppose the views are named say A, B, C and D in the order they are arranged. At a time, I need to show only, either B or C.
Implementation:
Used autolayout to add respective constraints via storyboard.
Created NSLayoutConstraint outlets for Height constraints of views B and C.
Changed the constant property of the constraint outlet when required, say as follows:
_heightConstraintOfC.constant = ORGINAL_VALUE_OF_C;
_heightConstraintOfB.constant = 0.00;
and
_heightConstraintOfB.constant = ORGINAL_VALUE_OF_B;
_heightConstraintOfC.constant = 0.00;
What I Get:
The views are behaving as expected, But when I change the height constant to zero, the subviews remain in the same position, behind the new overlapped view.
In the screen shot, Login button lies within view B, but is visible, even though view C overlaps it.
What I Tried:
I tried hiding the views , i.e. hide B when showing C. This works, but doesn't seem to be the right way when using autolayout.
I also tried using
[self.view layoutIfNeeded], [self.view layoutSubviews] and [self.view setNeedsLayout]. This didn't help.
What I understand is that you need to add constraints to everything within a view and then update each of them manually. This doesn't seem feasible to me.
Please provide your valuable suggestions or a solution to this problem. Thanks!

Related

How to set up my constraint perfectly to the bottom in Storyboard

I am using AutoLayout in Storyboard. I have set translateAutoResizingMasksToConstraints to false. I have created a constraint like so:
The superView takes up the whole screen's frame. When I run the App, the bottom bar view doesn't appear. However, if in the picture I change constant to 50, it jumps up to about where it should be expected.
I have had a previous branch where I did not set it to 50 but due to some other constraints it appeared as expected. But it's not exact and I don't know why it's behaving this way all of a sudden. I've used the View Debugger feature and the bottom bar view straight up doesn't appear at all.
How can I set it so that the constraint has a constant of 0 and still appears? What might be a reason for this bug? Thanks!
When you are trying to add constraints to two items, you try an easier way by choosing two of them(even super view) like this:
Then click 'add new constraints' on the right bottom of storyboard/xib,
Then you can choose different types of align constraints as you like.
If you only choose one item to add new constraint, then align will be disabled cause it needs two items.
Try printing the bar's frame in view did appear, if you are not sure whether the bar is just outside the visible field. Have you set constraints to the sides and a height as well? As a rule of thumb you can say that a view needs 4 constraints before iOS knows exactly where you meant for the view to be placed.

iOS - Storyboard - modify UIView that is out of frame with autolayout

It's a fairly stupid question but here we go:
I am using Autolayout right now to create a UIScrollview with 3 different UIViews I am scrolling through. I all created it using Storyboard and it works perfectly -- the first View is in the middle of the frame, and the 2 other ones are horizontally out of the frame. When I scroll in the Simulator it works perfectly.
All my frames have proportional widths to the main Superview, which means that they take the whole screen's space.
My issue is that I can't access the two other views to add elements to them through the Storyboard because they are not in the frame -- even if I change the ViewController's size, all the Views just get bigger because their size is proportional to the main view's size.
I would like to add elements to the right side of my second UIView (the third one is even more to the right), but you can't drag n drop objects if it's not on the ViewController's frame.
How could I solve this issue without having to mess up all my constraints?
Thanks a lot !
One way to deal with this is go to your storyboard -> select your firstView -> View Constraints and edit the 'Leading Constraint to Superview' constraint negative multiples of width of the screen like -320, -640. It will then show you the second and third view respectively.
Image attached below.
Note: You need to remember to set this back to 0 once you are done editing.
You can drag new views into the view hierarchy shown on the left, and use the same to select any items to edit them, add constraints, etc.

Autolayout Constraints "disappear" on scroll in UIPageViewController

I am trying to build a scroll view with a "floating" header using auto-layout. To be more exact I am trying to build a calendar view with several columns. Each of those column should have its own header which should float on top while the column can be scrolled vertically below it.
If everything works it looks like this:
As you can see there are several columns and a page control to indicate how many more pages of columns are available.
However when swiping/panning (or even just trying to swipe) to switch to the next page, the constraints keeping the header labels on top are removed and they disappear to the top of the scroll view (where they are in the storyboard).
Column headers are not visible due to being scrolled offscreen
Column headers are positioned at top of the scroll view (and the height is wrong).
Setup
A user can switch between dates ("Today" button at the top with left-right-arrows) and switch between the people displayed. (swipe/pan on view)
Boh interactions are realized with UIPageViewControllers inside one another. The outer page view controller switches between dates, the inner one between the pages of columns (with people).
The time view is contained in the outer page view controller but not the inner one.
So the hierarchy of views and controllers looks like this:
Calendar PageViewController (the one controlled via buttons in the navigation bar)
-- Scroll View of Page View Controller
---- Team View Controller (with view)
------ Header View reference (see screenshot 2)
------ Scroll View for vertical scrolling
-------- Time View (the one on the left)
-------- People PageViewController (the one controlled by swiping left/right)
---------- ScrollView of Page View Controller
------------ ViewController for a Single Page (with view)
--------------(1-n) Container View Controller (several of those, in the example 4 per page)
---------------- Column View Controller
------------------ Header View (A UIVisualEffectsView with a label)
------------------ calendar column view (the one doing the horizontal stripes)
Two pin the header views of the individual column view controllers to the top I use a reference view outside of the inner page view controller and outside of the vertical scroll view. I called it Header View reference in the overview above and you can see it quite nicely in the broken example:
It's a simple UIVisualEffectsView that I constrained to be at the top left with a fixed height and same width as the time view. So this view has the correct position and height I want all my header views to have and I use that to constraint the individual column header views to it in code (all other constraints are set up in storyboards) in the updateViewConstraints method of each ColumViewController like so:
- (void)updateViewConstraints
{
DDLogDebug(#"updating view constraints in colum view controller for %#", self.employee.displayName);
UIView *baseView = self.headerViewReferenceContainer.viewForHeaderContainerViewConstraints;
UIView *containerReference = self.headerViewReferenceContainer.headerContainerViewReference;
NSParameterAssert([containerReference isDescendantOfView:baseView] && [self.headerContainerView isDescendantOfView:baseView]);
[baseView addConstraint:[NSLayoutConstraint constraintWithItem:self.headerContainerView
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:containerReference
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:0]];
[baseView addConstraint:[NSLayoutConstraint constraintWithItem:self.headerContainerView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:containerReference
attribute:NSLayoutAttributeHeight
multiplier:1.0
constant:0]];
[super updateViewConstraints];
}
baseView is the view to which the constraints should be added. It must be a superview of both the header reference view and the header view of the column view controller. At the moment this will be the view of the Team View Controller above (the one containing the vertical scroll view).
containerReference is the Header View Reference view as seen in the screenshot above.
So I constrain the column header views to have the same top position and same height as the reference view. (the width and x position depends on the column)
As you can see in the broken screenshots the Header View reference is always positioned correctly. Also, on loading the view controllers and there views, the constraints are setup correctly.
Then when starting a pan gesture which switches the page of the PeoplePageView Controller and loads the next ViewController for a Single Page the constraints somehow disappear and the header views move to the top of the scroll view due to no longer being pinned to the top.
The next View Controller for a Single Page has the constraints set up correctly, but only until it snaps into place.
So while panning the constraints of the view controller to display are setup correctly. But as soon as it snaps into place (feels like it happens at -viewDidAppear) the constraints are removed as well.
I don't understand why and how the constraints are removed.
What is not wrong / what I tried
It could be due to one of the related views disappearing, but
the baseView doesn't change at all on swiping left right as it is a superview of the paging scroll view
the header reference view is not changed as it is not contained in the paging Page View Controller.
the header column view does not disappear until the view controller is fully offscreen, so the layout should not break during the paging
I used to have an issue with the layout only falling into place AFTER the paging finished. This was due to my constraints relating to the top layout constraints as described in iOS 8 UIPageViewController Applying Constraints After Transitions.
As a result I use a fixed distance from the super view's top to pin my Header View Reference instead of pinning it to the top layout constraint.
So the bug of the UIPageViewController not having a correct top layout constraint on paging shouldn't be the issue either.
I do not add any views programatically. All my Storyboards use auto layout and view controller are added to each other via Container View Controllers in the Storyboard or implementing a UIPageViewControllerDatasource and instantiating the view controller from a xib. So there shouldn't be any issues related to translatesAutoResizingMasks. Also, it works on load, it only breaks on paging, this doesn't fit the usual translatesAutoResizingMasks = YES problem.
I also do not get any errors about conflicting constraints or the view hierarchy not being prepared for constraints, the working constraints are simply removed.
I due have one issue which I think is unrelated, but I'll list it here for completeness' sake: I get an error due to the layout constraints of the labels inside the column header views being added to early:
The view hierarchy is not prepared for the constraint: <NSLayoutConstraint:0x7af4df20 UILabel:0x7af4e0d0'Susanne'.width == UIVisualEffectView:0x7af4de70.width>
When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. Break on -[UIView _viewHierarchyUnpreparedForConstraint:] to debug.
However, that message complains about the relation between the label and its containing view (the header view of the column), not about the "outer" constraints of the header view. Also, it warns that the app will crash if the constraints need to be resolved too early. The app does not crash, so the timing seems to be right. Also, the constraints the app complains about are setup in a storyboard, so I don't see how I could get the timing wrong.
tl;dr: Constraints that reach through several levels of the view hierarchy from inside a UIPageViewController to a view outside of it are removed (without warning, comment, reason or anything).
I don't understand why and how to prevent that from happening or at what point to add them again.
UPDATE:
I added the following call to viewWillAppear::
[self.view setNeedsUpdateConstraints]
This has the following effect:
When dragging the page to the side a bit (not switching the paging) and releasing it again (so it snaps back) the broken constraints are repaired again (and the layout is fixed). This is due to the page view controller calling viewWillAppear: on the original view controller if it "snaps back" (to offset the previously issued viewWillDisappear call).
But during the scrolling the layout is still broken.
Also when swiping to a new page, the constraints of the new page are also broken.
But whenever viewWillAppear is called the constraints are fixed for a short time until they are removed again (usually when the scroll ends).
If I add the same call to viewDidAppear instead of viewWillAppear the following happens:
This leads to the layout being correct most of the time (they are fixed after scrolling ends).
But it is still broken during scrolling.
Now if I add [self.view setNeedsUpdateConstraints] to both methods the following happens:
The layout behaves correctly almost all of the time, no strange jumping around of views
Except for the first page change. During that one the constraints of the original page seem to be removed and the layout is broken in the way shown above. After that, the constraints seem to be fixed permanently and swiping back and forth works without issues.
This is even true for three pages (I also tried it with four) when paging to the last page (and trying to go beyond it) and back although I'm pretty sure the page view controller does not keep all three pages in memory.
Is there a chance that updateViewConstraints is being called more than once causing multiple additions of the same constraints which is then causing an issue. I believe this can happen quite easily.
I notice in numerous discussions that many seem to recommend not doing the create and add in this function, (viewDidLoad seems preferred) and to only do the constraint value settings in this function to minimize the issue of multiple calls but to ensure the sizes are correct. Another option seems to be to put a Boolean guard for the controller around constraint addition to make sure it only occurs once in the lifetime of the controller.
Might not be your issue, but thought worth mentioning.
Try setting your constraints in viewDidLayoutSubviews. I am not quite certain but I remember solving a constraint related issue this way and it seemed to work.
Why don't you set the top of the headerView to the top of the baseview. i.e. the view that contains the scrollview. This will fix your issue for sure.
Ok, I still think it is a bug, but I found a workaround:
I basically have two constraint I want to keep and which sometimes disappear. I create properties for these, but make them weak:
#property (weak) NSLayoutConstraint *headerViewHeightConstraint;
#property (weak) NSLayoutConstraint *headerViewTopConstraint;
I then assign the created constraints to these properties in updateViewConstraints like this:
NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem:self.headerContainerView
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:containerReference
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:0];
[baseView addConstraint:topConstraint];
self.headerViewTopConstraint = topConstraint;
By using a weak reference I can check whether the constraint exists without keeping it around if nothing else references it. This way, when the constraint is removed from the view (for whatever reason) it will be deallocated an my property will be nil. I can use that to check whether I need to reestablish the constraint like this:
- (void)reestablishHeaderViewConstraintsIfNecessary
{
if (!self.headerViewTopConstraint || !self.headerViewHeightConstraint) // if any of the constraints is missing
{
[self.view setNeedsUpdateConstraints];
}
}
Now I just need a place to call that method from, to make sure it is called whenever the constraints might have been removed. As described in the question viewWillAppear and viewDidAppear are not good enough. Instead I use viewWillLayoutSubviews. This is called whenever the bounds change (e.g. many times during scrolling), which is quite often, but because I wrap the actual constraint invalidation this should be cheap enough if nothing needs to be done:
- (void)viewWillLayoutSubviews
{
[self reestablishHeaderViewConstraintsIfNecessary];
[super viewWillLayoutSubviews];
}
I think it is important to use viewWillLayoutSubviews, not viewDidLayoutSubviews ad invalidating the layout in viewDidLayoutSubviews leads to an exception but I'm not sure. This is also the reason why I put the call in front of the call to [super viewWillLayoutSubviews], but I didn't try whether it would work with the call appearing after it.

hide a view and remove blank spaces

I'm developing an app for iOS and I'm using the Storyboard with AutoLayout ON. One of my view controllers has a set of 3 labels, and in certain circumstances i would like to make the second one disappear.
If I use the setHidden:TRUE method the label become invisible but it still obviously take space in the view.
can someone point me to the right direction?
The simplest solution is to put the views that you want to hide inside a StackView. Then to hide the element simply make it hidden:
_myElement.hidden = YES;
StackView will squash hidden elements and they will become invisible.
I think you can link the constraint with the header file of your viewController. Then modify the constraint and commit changes.
Edited:
1) Create the IBOutlet for the constraint.
2) Modify the constraint, for example: self.yourConstraint.constant = 0.0;
3) Commit the new constraint: [viewForUpdate setNeedsUpdateConstraints];
The easiest and most effective way to handle this is using Stack Views. Insert the label in a horizontal/vertical (orientation they appear on your UI) stack view and stack view will internally take care of the spacing. Additional properties like alignment, spacing can be tweaked as per requirement. Make sure you re-establish the constraints between stack view and adjacent elements because once the views are added to a stack view all if its constraints are cleared
You will need to move the other views by adjusting their frames. This can be done directly, or if using auto layout, by giving them a vertical spacing constraints to the view being hidden.
If there are many other views that depend on the hiding/showing view, create another subview that contains all of the dependent views. The dependent views can layout statically on that parent, and that parent can have it's frame adjusted (again, either directly or via auto layout).
view
|
--- view to hide
|
--- common parent (move this with auto layout or directly)
|
--- subview's with position dependent on view to hide
--- ...
This is a late answer/solution, but I have just built a category which does just that - hiding the view without blank spaces.
https://github.com/neevek/UIView-Visibility

What happens with constraints when a view is removed

The question I have is simple but I couldn't find any information in the documentation.
What happens with layout constraints when a view is removed from the view hierarchy (or moved to another view)?
For example, let's have container C with subviews A and B. Container C holds some constraints. Then we call [A removeFromSuperview]. What happens with the constraints for A?
What then happens if we add A to C again?
The constraints are removed. If you add A again, you will have to make new constraints for it, or if you save the constraints before you remove A, you can add them back. When I do something like this, I save the constraints like this for a view called view1:
self.portraitConstraints = [NSMutableArray new];
for (NSLayoutConstraint *con in self.view.constraints) {
if (con.firstItem == self.view1 || con.secondItem == self.view1) {
[self.portraitConstraints addObject:con];
}
}
Since I had this question too, I checked the Apple Docs just for kicks, and it turns out that it is documented that the constraints are removed.
The documentation for the UIView removeFromSuperview method states:
Calling this method removes any constraints that refer to the view you
are removing, or that refer to any view in the subtree of the view you
are removing.
I'm not sure if this was documented last year when the original question was posted, but I just thought I'd share this information in case anyone needed it...
Be aware though, that if you have two independent parent views A and B, and a subview C, where C is currently a subview of A, with appropriate constraints, that calling [B addSubview:C] will NOT clear any constraints relating to A and C, and auto layout will start throwing exceptions, because those constraints no longer relate to views in the same hierarchy.
You will need to call [C removeFromSuperview] explicitly to remove the constraints, before adding C to B.
This is true on Mac OS X - I haven't checked iOS
The constraints are also removed when you [A removeFromSuperview]
They are forgotten and adding A to C again adds no constraints.
They are removed too, you can do a simple test. Pick up a view SUBVIEW and create costraints that constraint SUBVIEW to follow its superview resizing (like attched to to superview edges). To do that you add SUBVIEW as a subview to this CONTAINERVIEW and add as constraints something like that:
V:|-[SUBVIEW]-|
H:|-[SUBVIEW]-|
These constraints should be added to SUBVIEW superview, thus CONTAINERVIEW.
If you remove SUBVIEW by simply checking all the CONTAINERVIEW constraints you could see that two aren't around anymore.
This question also can be proved by interface builder. When drag and drop a UIView on the ViewController add constraints then remove the UIView, you can see the blue constraints disappear.

Resources