Springs in Auto Layout: Distribute views evenly, with constraints, in Xcode 5 - ios7

I understand the old Struts and Springs method of aligning, sizing and distributing views in Interface Builder. However, I cannot seem to figure out how to evenly distribute views using auto layout with Xcode 5. There was a way to do it using Xcode 4, but that option is gone.
I have 7 buttons arranged in a vertical stack. On a 3.5" layout, it looks great. When I preview the screen in the 4" layout, all of the buttons remain tightly packed and there is a large amount of space below the last button.
I want them to stay the same height, but I want the space between them to be able flex so they can spread out across the screen.
I've been able to get the height of the buttons to flex and fill the space, but that is not my desired behavior. I would like to learn how to use Auto Layout to replace my old Springs behavior, but I can't seem to find any way to do it through Interface Builder.
I'm ok with the top button either being a fixed space from the top edge or a proportional space from the top edge, likewise for the bottom button and the bottom edge. Those are less important to me, I'm good with either.
But I really need to figure out how to evenly distribute the extra space between each of the items in the view.

EDIT Note that in iOS 9 this technique will become unnecessary, because a UIStackView will perform distribution automatically. I'll add another answer explaining how that works.
How to Perform Even Distribution Using Autolayout
The simplest way to do this in Interface Builder alone (rather than constructing constraints in code) is to use "spacer" views:
Position the top and bottom buttons absolutely.
Place spacer views between all the buttons. Use constraints to position them horizontally (centering them horizontally is simplest) and to set their widths.
Make constraints between each button and the spacer view above and below it, with a Constant of 0.
Now select all the spacer views and set their heights to be equal.
The first screen shot shows me setting this up in IB:
I have deliberately not corrected for the "misplaced views" because I want you to see what it looks like while I'm designing the constraints. Here's the result on both a 4 inch and a 3.5 inch screen:
I have left the spacer views black, just to show you how this technique works, but of course in real life you would make them transparent and hence invisible! So the user sees just your buttons, evenly distributed on either height of screen.
The reason for the use of this technique is that although the notion of equality performs the distribution of values you are asking for, constraints can apply equality only between aspects of views; thus we need the extra views (the spacer views) so that we have things we can make equal to other things (here, the heights of the spacer views).
Other Approaches
Obviously, a more flexible approach is to assign the constraints in code. This may sound daunting, but there's a lot of third-party code out there to help you, such as this sort of thing.
For example, if we have a (possibly invisible) superview whose height acts as a boundary to dictate maximum vertical distribution of our four buttons, we can pin their tops to the vertical center of that superview with a constant of 0 but a multiplier of 0.000001, 0.666667, 1.33333, and 2.0 respectively (if we have four buttons); now the buttons will stay vertically distributed even as the superview changes size in response to screen height or whatever. [In Xcode 5.1, it will be possible to set that up in Interface Builder, but in earlier versions of Xcode it is not possible.]

In iOS 9 / Xcode 7 this problem will be trivially solved in IB. Simply select the buttons (or whatever it is you want to distribute vertically) and choose Editor > Embed In > Stack View. Then you simply configure the stack view:
Provide constraints that position and size the stack view itself. For example, pin the four edges of the stack view to the four edges of its superview.
Set the stack view's attributes. In this case we want Vertical axis, Fill alignment, Equal Spacing distribution.
That's all! However, you may be curious about how this works, because it is still possible to do the same thing manually in code. A stack view performs distribution, not by inserting spacer views, but by inserting spacer guides. A guide (a UILayoutGuide) is a lightweight object that behaves like a view for purposes of layout constraints, but is not a view and therefore doesn't have to be made invisible and doesn't carry any of the overhead of a view.
To illustrate, I'll do in code what the stack view is doing. Presume we have four views to distribute vertically. We assign them constraints for everything but their distribution:
They all have absolute height constraints
Their left is pinned to the superview's left, and their right is pinned to the superview's right
The top view's top is pinned to the superview's top, and the bottom view's bottom is pinned to the superview's bottom
Now, presume we have references to the four views as views, an array. Then:
let guides = [UILayoutGuide(), UILayoutGuide(), UILayoutGuide()]
for guide in guides {
self.view.addLayoutGuide(guide)
}
NSLayoutConstraint.activateConstraints([
// guide heights are equal
guides[1].heightAnchor.constraintEqualToAnchor(guides[0].heightAnchor),
guides[2].heightAnchor.constraintEqualToAnchor(guides[0].heightAnchor),
// guide widths are arbitrary, let's say 10
guides[0].widthAnchor.constraintEqualToConstant(10),
guides[1].widthAnchor.constraintEqualToConstant(10),
guides[2].widthAnchor.constraintEqualToConstant(10),
// guide left is arbitrary, let's say superview margin
guides[0].leftAnchor.constraintEqualToAnchor(self.view.leftAnchor),
guides[1].leftAnchor.constraintEqualToAnchor(self.view.leftAnchor),
guides[2].leftAnchor.constraintEqualToAnchor(self.view.leftAnchor),
// bottom of each view is top of following guide
views[0].bottomAnchor.constraintEqualToAnchor(guides[0].topAnchor),
views[1].bottomAnchor.constraintEqualToAnchor(guides[1].topAnchor),
views[2].bottomAnchor.constraintEqualToAnchor(guides[2].topAnchor),
// top of each view is bottom of preceding guide
views[1].topAnchor.constraintEqualToAnchor(guides[0].bottomAnchor),
views[2].topAnchor.constraintEqualToAnchor(guides[1].bottomAnchor),
views[3].topAnchor.constraintEqualToAnchor(guides[2].bottomAnchor)
])
(Obviously I could make that code cuter and shorter using loops, but I have deliberately unrolled the loops for clarity, so that you can see the pattern and the technique.)

Related

XCode8: UICollectionView edge-to-edge, Editing constraints in One Trait Variation (Size Class) breaks other Trait Variations

I am having an infuriating issue with Xcode interface builder. I have a storyboard where one view controller has a UICollectionView that's edge to edge to the View Controller's Root View. The root View has Descendant constraints of -16 and -16 for Leading and Trailing space to the UICollectionView.
When I switch to the other size class (Or Trait Variation as it's now called), the Leading and Trailing margins become -20, -20. If I adjust them to be edge to edge, then the other Trait Variation becomes inset by 4 pixels on each side. So editing the constraints in one variation screws up the other variation, and thus all my internal calculation logic is off for the cells.
So i can not simultaneously satisfy the constraints in multiple trait variations all at the same time, and have my UICollectionView just be edge-to-edge without any padding around it.
I tried remaking all constraints. Same issue.
I tried turning off Trait Variations on the storyboard itself. Same issue.
EDIT: Also tried adding an "Intermediary View" (also edge-to-edge) and housing my UICollectionView inside it. Makes no difference.
I noticed that the negative inset amount has to be different on each device factor. On some it's -16 -16, on some it's -20, -20, on iPad it's -8, -8. So since these are static values, then how can you embed a scrollview edge to edge reliably, without fiddling with the constraints programmatically at runtime?
I can fix one device screen size, but it breaks the other screen sizes.
Also, i don't actually want to use size classes, but even if i turn off size classes, i still don't get one unified view for editing the constraints in one place. So this effectively multiplies the work i have to do by 6 times. This is costing me a ridiculous amount of time already.
Any suggestions?
I found a cheap and easy solution. My problem was: my Leading and Trailing constraints were to the Margin, and not to the superview directly. The margin is what differs across size classes. So I modified my 2 constraints: Leading and Trailing, disabling the "Relative to Margin" option on each. Instructions here: UIViewController Nested View To Screen Edge
Now i get a consistent behaviour on every screen size (no margins around collection view).

How to implement scroll view in xib cocoa objective-c

In order to implement scroll view I do:
Create Cocoa Application
Go to XIB
Drag scroll view to the view window and set its constraints to 0
Everything seems fine until now
Under Bordered Scroll View (in the Document Outline) I press on Clip View and then View and resize that to any large number (under size inspector)
I add a button (for the sake of it) to the view (under clip view) (in the Document Outline) and sets its constraints
After this I immediately get the "Ambigious Layout. Position is ambigious for "View".
What am I doing wrong? Is this the proper way to add scrollview? It also seems rather difficult to add items to the scrollable area as I dont see the entire scrollable area in the xib.
Please help a noob.
In general this is a correct way to add a scroll view. (You can also create a view or set of sibling views, select them, and choose Editor > Embed In > Scroll View.)
If a view has no constraints, then Xcode will add sufficient constraints at build time. These constraints are not necessarily the ones that cause the view to behave like you want as things change size, but they're good enough to maintain the current layout of the canvas when things have their current sizes.
However, once you add constraints, Xcode will start insisting that the constraints are mutually-compatible (no conflicts) and sufficient to be unambiguous.
So, that explains why you get that warning. You have added some constraints, but not enough to make the layout unambiguous. You need to add enough. Xcode should explain in more detail what's needed, although there will necessarily be multiple possibilities for how to resolve the ambiguity.
In your case, I'm guessing that the size of the view in the scroll view is ambiguous. For example, you may have added constraints to position the button relative to the top and leading edge, and the button likely has intrinsic size, but you haven't constrained the view's bottom or trailing edges to the button. So, the size of the view could be anything.
Of course, rather than constraining the view's bottom and trailing edge to the button, you could just add explicit height and width constraints to it. Or whatever.
You may also need to constrain the view to the clip view.
You can also use Editor > Resolve Auto Layout Issues > Add Missing Constraints and see what Xcode adds. You can then change things from there if what Xcode added is not what you want.
For my Mac OS X app, I selected the controls on xib to embed in scroll view ( Editor > Embed In > Scroll View ) and applying the following constraints to Custom View (inside Scroll View -> Clip View) did work.
Where hight is to accommodate controls.

Full responsive UIView inside a UIScrollView using autolayout

I'm trying to understand how autolayout works under XCode6, but there's a lot of mysterious things that runs away from my mind. Autolayout and constraints philosofy can be very hard to learn, but I realized that life can be easier using these tools...
For your information, I need to build a chat view with a table (the messages) and a view containing a text field (the send message pane) nested in a UIView that is again nested in a UIScrollView, so I can shift up the scroll view as the keyboard appears under the textfield.
I read a lot of tutorials and watched a lot of video until I found the useful tutorial Using UIScrollView with Auto Layout in iOS. There's a Xcode project in Github of what the tutorial explains, too.
In his tutorial, Mike Woelmer tells that
One of the big pain points with the old way of setting up a
UIScrollView was communicating the content size to the scroll view. It
was fairly straightforward to calculate your content size if the
content in the UIScrollView was an image. But it was not as easy if
your scroll view included a mixed bag of buttons, labels, custom
views, and text fields. Lengthy code adjustments were needed to
reflect constant changes in device rotations and phone size
differences.
So Mike explains the way to adapt the UIView, using placeholder and forcing the view inside the scrollview to fits the device's screen, creating in viewDidLoad some NSLayoutConstraint:
The solution is to look outside the scroll view and attach a
constraint to the view controller’s main view. This cannot be done in
interface builder, so we will have to write some code. Interface
builder is still complaining, though, so we have to add a placeholder
width constraint to make it happy.
I tried to use parts of the code of the tutorial for my project, but I cannot get a working view controller for my needs (I always get errors). Which is the best approach to do this? Am I on the right road?
Last but not least, I'm italian, so pardon for my english. If something is not clear enough, please leave me a comment.
Basically you have to set both alignment and size constraints in order for Autolayout to take care of the rest for you. If you don't provide enough information you get warning. If you provide conflicting information you get errors.
You need basically to provide enough information for Autolayout to calculate the UIView frame property (i.e., x-position, y-position, width, height).
For example, by providing the distance constraints from the top, right, bottom, and left edges, Autolayout has enough information to draw that UIView's frame rectangle. But you could also provide just the distance constraints from the top and left edges and then provide a size and height constraint.
You can also configure the key constraints you need and then click 'resolve auto layout issues' and choose 'add missing constraints' though sometimes it doesn't give you what you want. It is better to understand that how Autolayout accomplishes what I described above.
If you mess up, it's usually easier to clear all the constraints and start over. Do it a few times and you'll get the hang of it.

UIToolbar not resizing when rotating with autolayout, with UIBarButtonItems misplaced

it's the first time I'm seriously using autolayout so I'm sure I'm missing something obvious.
I have a very simple view embedded in a UINavigationController. There are three subviews: a UIWebView, a UIToolbar (which in turn contains three UIBarButtons) and a UIActivityIndicatorView. It's just a basic browser view, basically.
I managed to have everything appear as it should even on rotation, except for the toolbar: if the view is first loaded in vertical orientation, going landscape will not resize the toolbar from 44 to 32 points. Originally, before I wiped everything out, it did resize the toolbar BUT the built-in UIBarButtonItems appeared lower and cut off, as if the toolbar was still 44 points tall but pushed 16 points out of the screen.
If the view is first loaded horizonttaly, the bar is 32 points high but the built-in UIBarButtonItems appear still like that, and rotating to vertical will keep it at 32 points.
I honestly have no idea how to make this work as expected (ie. resize properly when rotated, with the buttons showing properly!), so if anyone could point me in the right direction -- pun intended -- I would be really grateful.
The activity indicator is right in the middle of the frame, with these constraints:
Align Center X to Superview
Align Center Y to Superview
The web view is set to use all available space from the top of the view (including the navbar) up to the top of the toolbar, and has these contraints:
Top Space to Superview
Bottom Space to Toolbar
Align Trailing to Toolbar
Bottom Space to Toolbar (it's actually listed twice)
Align Leading to Toolbar
The toolbar is a mess. It has:
Bottom space to Superview
Align Center X to Superview
Top Space to Web View
Align Trailing to Web View
Top Space to Web View (listed twice)
Leading Space to Superview
Align Leading to Web View
Bottom Space to Bottom Layout Guide
The problem is that by not adding any constraints at all, the web view is much bigger than it should be, and the toolbar doesn't even show.
I mostly set these constraints using the horizontal and vertical red bars (similar to springs and strouts) in the 'pin' popover for autolayout, but I'm starting to think that's not the most appropriate approach.
Note that I'm not trying to use autolayout within the toolbar, I read that it wouldn't work and I'm just using the built-in buttons plus a couple of labelled ones (those 'arrows' are really unicode characters, I may change them to prettier images at some point.)
Thank you in advance. :-)

Change size of window in Cocoa?

I have a window whose size I need to change when the user clicks on it. I am using [self setFrame:windowFrame display:YES animate:YES] to accomplish this.
Even though the window successfully changes size (I increase its height), it moves the contents of the window up with it. How do I prevent this from happening? I want the contents to remain in place.
I am on OSX Mountain Lion developing an app for OSX using Objective-C and Cocoa.
EDIT: Constraints and/or Springs and Struts will not work as I need to move the contents around after the window is resized.
Constraints and/or Springs and Struts will not work as I need to move the contents around after the window is resized.
In that case, you should use NSViewAnimation.
A single view animation can actually perform multiple animations to multiple views, and you can even do one to a window, despite the class's name and the fact that windows aren't views in Cocoa.
You create a view animation with initWithViewAnimations:, which takes an array of dictionaries. Each dictionary identifies the target (NSViewAnimationTargetKey) and what to do to it: Either change the target's frame (NSViewAnimationStartFrameKey and NSViewAnimationEndFrameKey) or fade the target in or out (NSViewAnimationEffectKey). For your case, you'll be changing the targets' frames.
When the user does the thing that causes the resize of the window, you'll need to compute the desired overall size of the window (taking care to adjust its frame's position so it doesn't grow off the screen), as well as the new frames—both positions and sizes—of your views. Everything that will move and/or change size, create a dictionary for it and throw it into the array. Then create the view animation.
An NSViewAnimation is a kind of NSAnimation, which provides all the methods for starting and stopping the animation, monitoring its progress, hooking into it, and chaining multiple NSAnimations together. If nothing else, you'll need to start the animation.
If you are using the Interface Builder to build these views, then I believe one approach is to set the "struts and springs." These are available under the "size inspector" and are the red arrows and bars above the "autosizing" label. Play around with these to get the effect that you want, but the general idea is that the arrows control how the size of the view adjusts to changes in the size of the parent view, and the bars control the relationship of the edges of the view to the edges of the parent view as the size changes.
In constraint-based layout, set the views around the edge of your window to be a fixed distance from their superview's edge.
Xcode will infer a lot of resizability from that; if anything still isn't resizing properly, adjust its constraints so that its width and/or height is no longer constant.
The easiest way is to move your views until blue lines show up in the editor. Each blue line corresponds to a rule in the HIG about how things should be lain out, and if you drop the view there, Xcode will create constraints matching those guidelines. For example, if you set a view 20 points from the right edge of its superview, you'll get a blue line for that, and if you drop the view there, you'll create a constraint that the view must remain that distance from that edge.
The superview isn't the only view with which you can create HIG-based constraints. You can also create guideline constraints between sibling views. For example, if you put a button next to another button at the appropriate distance, you'll get a blue line across that distance, and if you drop it, you'll create a constraint that those two buttons must remain that distance from each other.
If you want to do something really custom, the three buttons in the lower-right corner of the nib editor will let you create any constraint you want. What you have selected determines what constraints you can create; the nib editor's outline view will help you make sure you have the selection you want.
You are going to have to iterate through all of your subviews and change their frame positions based on the delta of your window frame.
so if you expand your window frame by 20 in all directions, all your subviews are going to have to increase their frame positions by (20,20) to offset the windows movement.