UIStackView - layout constraint issues when hiding stack views - ios

My app has 2 screens:
TableViewVC (no stack views here)
DetailVC (all the nested stack views here; please see link for picture: Nested StackViews Picture) -- Note, there are labels and images within these stack views.
When you press a cell in the tableview, it passes the information from the TableViewVC to the DetailVC. The problem is with hiding the specific UIStackViews in the DetailVC. I want only 2 stack views out of the various ones in the DetailVC to be hidden as soon as the view loads. So I write this code in the DetailVC to accomplish this:
override func viewDidLoad() {
super.viewDidLoad()
self.nameLabel.text = "John"
self.summaryStackView.hidden = true
self.combinedStackView.hidden = true
}
Everything looks great but Xcode give many warnings only at runtime. There are no warning in Storyboard when the app is not running. Please see link for picture of errors: Picture of Errors
Basically it's a lot of UISV-hiding, UISV-spacing, UISV-canvas-connection errors. These errors go away if I hide the same stack views in viewDidAppear but then there is a flash of the stuff that was supposed to be hidden and then it hides. The user sees the the view briefly and then it hides which is not good.
Sorry for not being able to actually post pictures instead of links, still can't do so.
Any suggestions on how to fix this? This is for an app I actually want to launch to the app store - it's my first so any help would be great!
Edit/ Update 1:
I found a small work around with this code which I put inside the second screen called DetailVC:
// Function I use to delay hiding of views
func delay(delay: Double, closure: ()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
// Hide the 2 stack views after 0.0001 seconds of screen loading
override func awakeFromNib() {
delay(0.001) { () -> () in
self.summaryStackView.hidden = true
self.combinedStackView.hidden = true
}
}
// Update view screen elements after 0.1 seconds in viewWillAppear
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
delay(0.1) { () -> () in
self.nameLabel.text = "John"
}
}
This gets rid of the warnings about layout constraints completely from Xcode.
It's still not perfect because sometimes I see a glimpse of the views that are supposed to be hidden -- they flash really quick on the screen then disappear. This happens so quickly though.
Any suggestions as to why this gets rid of warnings? Also, any suggestions on how to improve this to work perfectly??? Thanks!

I had the same problem and I fixed it by giving the height constraints of my initially hidden views a priority of 999.
The problem is that your stackview applies a height constraint of 0 on your hidden view which conflicts with your other height constraint. This was the error message:
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:0x7fa3a5004310 V:[App.DummyView:0x7fa3a5003fd0(40)]>",
"<NSLayoutConstraint:0x7fa3a3e44190 'UISV-hiding' V:[App.DummyView:0x7fa3a5003fd0(0)]>"
)
Giving your height constraint a lower priority solves this 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, Leading, 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.

You can use the removeArrangedSubview and removeFromSuperview property of UIStackView.
In Objective-C :
[self.topStackView removeArrangedSubview:self.summaryStackView];
[self.summaryStackView removeFromSuperview];
[self.topStackView removeArrangedSubview:self.combinedStackView];
[self.combinedStackView removeFromSuperview];
From Apple UIStackView Documentation:(https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIStackView_Class_Reference/#//apple_ref/occ/instm/UIStackView/removeArrangedSubview:)
The stack view automatically updates its layout whenever views are added, removed or inserted into the arrangedSubviews array.
removeArrangedSubview: This method removes the provided view from the stack’s arrangedSubviews array. The view’s position and size will no longer be managed by the stack view. However, this method does not remove the provided view from the stack’s subviews array; therefore, the view is still displayed as part of the view hierarchy.
To prevent the view from appearing on screen after calling the stack’s removeArrangedSubview: method, explicitly remove the view from the subviews array by calling the view’s removeFromSuperview method, or set the view’s hidden property to YES.

When the UIViewStack is hidden, the constraints automatically generated by the UIStackView will throw lots of UISV-hiding, UISV-spacing, UISV-canvas-connection warnings, if the UIStackView's spacing property has any value other than zero.
This doesn't make much sense, it's almost certainly a framework bug. The workaround I use is to set the spacing to zero when hiding the component.
if hideStackView {
myStackView.hidden = true
myStackView.spacing = CGFloat(0)
} else {
myStackView.hidden = false
myStackView.spacing = CGFloat(8)
}

I've found that nested UIStackViews show this behavior if you set the hidden property in ✨Interface Builder✨. My solution was to set everything to not hidden in ✨Interface Builder✨, and hide things in viewWillAppear selectively.

This error is not about hiding, but about ambiguous constraints. You must not have any ambiguous constraints in your view.
If you add them programmatically you should exactly understand what constraints you add and how they work together.
If you do not add them programmatically, but use storyboard or xib, which is a good place to start, make sure there are no constraint errors or warnings.
UPD: You have a pretty complex structure of views there. Without seeing the constraints is hard to say what exactly is wrong. However, I would suggest to build you view hierarchy gradually adding views one by one and making sure there are no design-time/runtime warnings.
Scroll view may add another level of complexity if you do not handle it correctly. Find out how to use constraints with a scroll view.
All other timing hacks is not a solution anyway.

I moved all UIStackView.hidden code from viewDidLoad to viewDidAppear and broken constraints problem went away. In my case all conflicting constraints were auto generated, so no way to adjust priorities.
I also used this code to make it prettier:
UIView.animateWithDuration(0.5) {
self.deliveryGroup.hidden = self.shipVia != "1"
}
EDIT:
Also needed the following code to stop it from happening again when device is rotated:
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
self.deliveryGroup.hidden = false
coordinator.animateAlongsideTransition(nil) {
context in
self.deliveryGroup.hidden = self.shipVia != "1"
}
}

I fixed it by putting the hide commands in traitCollectionDidChange.
override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
self.item.hidden = true
}

So, this may only help 0.000001% of users but maybe this is a clips to bounds issue.
I ran into this recently when working with UICollectionViewCell I forgot to check clips to bounds on the view I was treating as my content view. When you create a UITableViewCell in IB it sets up a content view with clips to bounds as the default.
Point is, depending on your situation you may be able to accomplish your intended effect using frames and clipping.

Put your hide commands in viewWillLayoutSubviews() {}

I did this by storing all the hidden views of the nested UIStackView in an array and removing them from the superview and arranged subviews. When I wanted them to appear again I looped through the array and added them back again. This was the first step.
The second step is after you remove the views of the nested UIStackView from the superview the parent UIStackView still doesn't adjust it's height. You can fix this by removing the nested UIStackView and adding it again straight afterwards:
UIStackView *myStackView;
NSUInteger positionOfMyStackView = [parentStackView indexOfObject:myStackView];
[parentStackView removeArrangedSubview:myStackView];
[myStackView removeFromSuperview];
[parentStackView insertArrangedSubview:myStackView atIndex:positionOfMyStackView];

If you're having issues animating HIDING AND SHOWING subviews at the same time, repeating the .isHidden instructions in the animation completion may help. See my answer here for more detail on that.

Have you tried this? Calling super after your changes?
override func viewWillAppear() {
self.nameLabel.text = "John"
self.summaryStackView.hidden = true
self.combinedStackView.hidden = true
super.viewWillAppear()
}

Related

Embedding Intrinsically Sized View Breaks Animation

I have built a test project to show what the goal is vs. what I currently have happening. The gif on the left shows exactly what I want the ending appearance to be. It is constructed with a single traditional view hierarchy. I need to achieve this with the pink view being an embedded/contained view. My attempts so far have only gotten me to the gif on the right.
The way the (pink) contained view grows is possibly an important detail: the blue subview changes it's height, and the whole apparatus gets a new intrinsic size because of all the connected vertical constraints. As you would expect, this is a simplification of my actual app, but I think it has all the important bits.
The main things I see that are strange:
The yellow/orange "other" view is not animating at all.
The pink contained view is animating nicely for it's own part, but it is animating it's position, even though it's frame has the same origin before and after the animation as shown here:
Here is the Storyboard of the right gif. Both the container view in the "parent" scene and the top view in the "child" scene have translatesAutoresizingMaskIntoConstraints set to false with runtime attributes.
The question then: **What must I change about my configuration to get all affected layout changes to animate (properly) when I have a size change in an intrinsically-sized and contained view? **
Edit: Tried manual embed
Since posting the question, I have tried a manual View Controller Containment strategy, and I got the exact same results as with the Storyboard technique, which is ultimately a good sign for the platform. There was 1 fewer view in the total hierarchy, but it didn't seem to make a difference.
Edit: Bounty and project
I have added a 100 point bounty to attract attention. I have also uploaded my sample project to this github repo. Check it out!
Changing your animation block in InnerViewController as follows does the trick.
var isCollapsed = false {
didSet {
let factor:CGFloat = isCollapsed ? 1.5 : 0.66
let existing = innerViewHeightConstraint.constant
UIView.animate(withDuration: 1.0) {
self.innerViewHeightConstraint.constant = existing * factor
self.view.layoutIfNeeded()
self.parent?.view.layoutIfNeeded()
}
}
}
The key difference is self.parent?.view.layoutIfNeeded(), which tells the embedding view controller to update the constraints as part of the animation, instead of immediately before the start of the animation.

Hide view without whitespace

WPF contains Hidden (hides the control, but reserves the space it occupies in the layout) and Collapsed (does not render the control and does not reserve the whitespace)
Swift contains isHidden property only (myView.isHidden = true).
How can I hide my control without whitespace?
If you're using storyboards and constraints, one clever way that I've found is to set the width or height constraint of the disappearing view to 0.
As an example:
#IBAction func onTapSquare(_ sender: Any) {
let constraint = disappearingView.constraintForIdentifier(id: "example_width")
constraint?.constant = 0
}
Note that you have to write the constraintForIdentifier function yourself, you can copy/paste from my view extension here:
Github link!
I whipped up a tiny example project which you can grab here:
Disappearing Constraint Example
If you've got margin in between the views, you can set that to 0 with a similar method. Good luck!
Here it is in action:

Xcode 8 - Some Views & VCs Not Showing Up on Simulator

The app ran perfectly prior to updating to Xcode 8 Beta 6 and Swift 3. I've changed nothing else but now I have two problems.
First, a few random views are no longer showing up. They're just square, colored boxes. The views above them show up though.
In Interface Builder:
On simulator:
Second, my model VC is no longer appearing when segued. It did before and I can see the segue is being called but now its' not there.
If anyone can provide ideas about either problem it'd be greatly appreciated.
So between Xcode 7/Swift 2 --> Xcode 8/Swift 3, something changed with how to turn a UIView into a circle. Here is my code now:
func roundView (_ viewToRound: UIView) {
viewToRound.layer.cornerRadius = 20
//viewToRound.layer.cornerRadius = (viewToRound.frame.width/2)
viewToRound.clipsToBounds = true
}
As you can see, I've replaced my cornerRadius method to be an explicit "20" instead of inferred from the view size. With my previous "frame.width" the views were literally not showing up at all. Now they're back to normal. I don't know what changed but this definitely fixed it.
Something may have happened to the auto layout constraints. Double check that those are set properly.
Also, you don't need to use the simulator to verify this; use the Assistant editor's Preview view:
As a sanity check, the first thing I would do is reset all of the elements in your view to the suggested constraints to see if that resolves the problem.
It's definitely an AutoLayout issue in Xcode 8. The problem doesn't exist without using AutoLayout. I made this workaround using a protocol:
protocol Roundable {}
extension Roundable where Self: UIView{
func roundCorners(){
self.layer.cornerRadius = self.bounds.height / 2
}
}
class CustomView: UIView, Roundable {
override var bounds: CGRect {
didSet{
roundCorners()
}
}
}
Make the view involved a CustomView and it will show up rounded. I use a protocol here, because in this way it's easy to extend an already existing UIView subclass with the functionality to round the corners. Of course it is possible to set the cornerRadius directly in the bounds property observer.
There is an issue with iOS 10 UIView lifecycle & AutoLayout.
What I mean by that is that in methods such as viewDidLoad & viewWillAppear the frames on all UI elements are `{{0,0},{1000,1000}}.
In cases such as with setting round corners makes rounded corners with 500px & you get invisible UI components :)
How I resolved this issue is by setting the rounded corners in viewDidLayoutSubview in UIViewControllers or layoutSubviews in UIView subclasses.

How to assign a higher level on a uiview in order to make it override another view?

I created a uiview and added a sub-uiview on it. Then I allow user to drag the sub-view around the screen freely. But I have problem when moving the sub-view on top of the screen. Please see below picture. The sub view override the top uiview on the screen. What I want is to let the top uiview to override the sub-view. How can I change the level of a uiview in this case?
when I use self.titleView.bringSubviewToFront(sv)
I see another problem as shown in below image. The status bar is not at the top of the image view.
You can use bringSubviewToFronton parent view to bring sub view to front as follow:
objective-C:
[parentView bringSubviewToFront:childView];
swift:
parentView.bringSubviewToFront(childView)
Edit:
use below method to manage views:
bringSubviewToFront(_:)
sendSubviewToBack(_:)
removeFromSuperview()
insertSubview(_:atIndex:)
insertSubview(_:aboveSubview:)
insertSubview(_:belowSubview:)
exchangeSubviewAtIndex(_:withSubviewAtIndex:)
like,
self.view.sendSubviewToBack(myView)
For more detail check: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/#//apple_ref/doc/uid/TP40006816-CH3-SW46
Hope this helps :)
parentView.bringSubviewToFront(view)
UPDATE
Pay attention: you must considered that parentView is the parent of your view. To explain better this concept if you have a line like this:
self.container.addSubview(view)
so self.container is the view parent's, dont confuse it with the view below your view...it may not be the same.
If your draggable view is a subview of the image view try to set masksToBounds to true:
imageView.layer.masksToBounds = True
But the reason of your issue is probably because you set zPosition of draggableView.layer to some positive number. Usually it is better to use methods such as insertSubview(_:aboveSubview:) and bringSubview(toFront:) to manage subview's order.

how to redraw custom view from the controller in ios objective-c

I have a custom view with 3 buttons taking full width.
I import the class to my controller where I want to hide on button (menuBtn) and make one of the one of the other buttons (searchbarBtn) be bigger to fill the empty space by doing:
`self.topMenuView.searchbarBtn.frame = CGRectMake(self.topMenuView.searchbarBtn.frame.origin.x, self.topMenuView.searchbarBtn.frame.origin.x, self.topMenuView.searchbarBtn.frame.size.width + self.topMenuView.menuBtn.frame.size.width , self.topMenuView.searchbarBtn.frame.size.height);`
I do this in viewWillLayoutSubviews (have also tried in viewWillAppear) and I call the
[self.topMenuView.searchbarBtn setNeedsDisplay];
but nothings happens.
I
The button's layout properties override your frame settings, since by definition viewWillLayoutSubvies is called before the layout pass. You should just set
self.topMenuView.menuBtn.hidden = YES;
and use autolayout constraints (in the interface builder or in the code) between menuBtn, searchbarBtn and topMenuView to make sure your buttons grow as needed.
As a general rule, we should strive to create interface so that views will correctly position themselves provided their inner state is correctly set and correct constraints are formed, without explicit corrections on our part.

Resources