UIStackView; Equal Spacing Between & Outside Elements - ios

UIStackView is awesome, I love Equal Spacing Distribution.
But how to achieve the same space also outside of elements dynamically?
In my case all elements will have same ratio 1:1

You can add equal spacing using the story board as shown here:
Source: https://stackoverflow.com/a/32862693/3393964

#Declan has the right idea. Here's that answer programatically where you add extra views on either side so the stack view gives correct outside spacing with any number of buttons.
stackView.alignment = .center
stackView.axis = .horizontal
stackView.distribution = .equalCentering
// Then when I add the views...
let leftView = UIView()
stackView.addArrangedSubview(leftView)
content.buttons.forEach { (button) in
stackView.addArrangedSubview(button)
}
let rightView = UIView()
stackView.addArrangedSubview(rightView)
Here's what my view looks like with 2 items using equalSpacing
And here it is with equalCentering distribution, also a nice look.

I prefer to let the UIStackView handle the spacing. Create a UIStackView with equal spacing and add two 0px wide (0px high if using a vertical stackview) transparent views to the the far sides of your stack view.

You can use constraints and give then same height and width. So when you change the dimension of anyone of the component then all components are changed with same dimension.

I think what you want is to have the same spacing outside of the stack view with the spacing outside.
What I would do is the put stack view inside another view (GRAY VIEW) and set the leading and trailing constraint of the stack view to be equal to the spacing of the stack view.
Spacing of the Stack View
Constraints of the Stack View from its super view (Gray View)

Related

UIScrollView with dynamically sized content

(Xcode 11, Swift)
Being a newbie to iOS and Autolayout, I'm struggling with implementing a fairly simple (IMHO) view which displays a [vertical] list of items. The only problem is that items are decided dynamically and each of them could be either text or image (where either of those could be fairly large so scrolling would be required). WebView is not an option, so it has to be implemented natively.
This is how I understand the process:
Make in IB a UIScrollView and size it to the size of the outer frame.
Make a container view as a subview of UIScrollView (again, in IB) and size it the same.
Set constraint on equal width of both
At runtime, populate container view with UILabels/UIImageViews and also set constraints programmatically to ensure proper layout.
"Tell" scrollview about the subview height in order to make it manage the scrolling thereof.
Is this the right approach? It doesn't seem to work for me (for a toy example of dynamically adding a very tall image to a container view - I cannot get the scrolling to work). What would be the proper way to do the last step in the process above - just force the contentSize of the scrollview to the size of the populated container view (it doesn't seem to work for me). Any help would be appreciated.
When adding multiple elements to a scroll view at run-time, you may find it much easier to use a UIStackView... when setup properly, it will automatically grow in height with each added object.
As a simple example...
1) Start by adding a UIScrollView (I gave it a blue background to make it easier to see). Constrain it to Zero on all 4 sides:
Note that we see the "red circle" indicating missing / conflicting constraints. Ignore that for now.
2) Add a UIView as a "content view" to the scroll view (I gave it a systemYellow background to make it easier to see). Constrain it to Zero on all 4 sides to the Content Layout Guide -- this will (eventually) define the scroll view's content size. Also constrain it equal width and equal height to the Frame Layout Guide:
Important Step: Select the Height constraint, and in the Size Inspector pane select the Placeholder - Remove at build time checkbox. This will satisfy auto-layout in IB during design time, but will allow the height of that view to shrink / grow as necessary.
3) Add a Vertical UIStackView to the "content view". Constrain it to Zero on all 4 sides. Configure its properties to Fill / Fill / 8 (as shown below):
4) Add an #IBOutlet connection to the stack view in your view controller class. Now, at run-time, as you add UI elements to the stack view, all of your "scrollability" will be handled by auto-layout.
Here is an example class:
class DynaScrollViewController: UIViewController {
#IBOutlet var theStackView: UIStackView!
override func viewDidLoad() {
super.viewDidLoad()
// local var so we can reuse it
var theLabel = UILabel()
var theImageView = UIImageView()
// create a new label
theLabel = UILabel()
// this gets set to false when the label is added to a stack view,
// but good to get in the habit of setting it
theLabel.translatesAutoresizingMaskIntoConstraints = false
// multi-line
theLabel.numberOfLines = 0
// cyan background to make it easy to see
theLabel.backgroundColor = .cyan
// add 9 lines of text to the label
theLabel.text = (1...9).map({ "Line \($0)" }).joined(separator: "\n")
// add it to the stack view
theStackView.addArrangedSubview(theLabel)
// add another label
theLabel = UILabel()
// multi-line
theLabel.numberOfLines = 0
// yellow background to make it easy to see
theLabel.backgroundColor = .yellow
// add 5 lines of text to the label
theLabel.text = (1...5).map({ "Line \($0)" }).joined(separator: "\n")
// add it to the stack view
theStackView.addArrangedSubview(theLabel)
// create a new UIImageView
theImageView = UIImageView()
// this gets set to false when the label is added to a stack view,
// but good to get in the habit of setting it
theImageView.translatesAutoresizingMaskIntoConstraints = false
// load an image for it - I have one named background
if let img = UIImage(named: "background") {
theImageView.image = img
}
// let's give the image view a 4:3 width:height ratio
theImageView.widthAnchor.constraint(equalTo: theImageView.heightAnchor, multiplier: 4.0/3.0).isActive = true
// add it to the stack view
theStackView.addArrangedSubview(theImageView)
// add another label
theLabel = UILabel()
// multi-line
theLabel.numberOfLines = 0
// yellow background to make it easy to see
theLabel.backgroundColor = .green
// add 2 lines of text to the label
theLabel.text = (1...2).map({ "Line \($0)" }).joined(separator: "\n")
// add it to the stack view
theStackView.addArrangedSubview(theLabel)
// add another UIImageView
theImageView = UIImageView()
// this gets set to false when the label is added to a stack view,
// but good to get in the habit of setting it
theImageView.translatesAutoresizingMaskIntoConstraints = false
// load a different image for it - I have one named AquariumBG
if let img = UIImage(named: "AquariumBG") {
theImageView.image = img
}
// let's give this image view a 1:1 width:height ratio
theImageView.heightAnchor.constraint(equalTo: theImageView.widthAnchor, multiplier: 1.0).isActive = true
// add it to the stack view
theStackView.addArrangedSubview(theImageView)
}
}
If the steps have been followed, you should get this output:
and, after scrolling to the bottom:
Alignment constraints (leading/trailing/top/bottom)
The alignment constraint between Scroll View and Content View defines the scrollable range of the content. For example,
If scrollView.bottom = contentView.bottom, it means Scroll View is
scrollable to the bottom of Content View.
If scrollView.bottom = contentView.bottom + 100, the scrollable
bottom end of Scroll View will exceed the end of Content View by 100
points.
If scrollView.bottom = contentView.bottom — 100, the bottom of
Content View will not be reached even the scrollView is scrolled to
the bottom end.
That is, the (bottom) anchor on Scroll View indicates the (bottom) edge of the outer frame, i.e., the visible part of Content View; the (bottom) anchor on Content View refers to the edge of the actual content, which will be hidden if not scrolled to.
Unlike normal use cases, alignment constraints between Scroll View and Content View have nothing to do with the actual size of Content View. They affect only “scrollable range of content view” but NOT “actual content size”. The actual size of Content View must be additionally defined.
Size constraints (width/height)
To actually size Content View, we may set the size of Content View to a specific length, like width/height of 500. If the width/height exceeds the width/height of Scroll View, there will be a scrollbar for users to scroll.
However, a more common case will be, we want Content View to have the same width (or height) as Scroll View. In this case, we will have
contentView.width = scrollView.width
The width of Content View refers to the actual full width of content. On the other hand, the width of Scroll View refers to the outer container frame width of Scroll View. Of course, it doesn’t have to be the same width, but can be other forms like a * scrollView.width + b.
And if we have Content View higher (or wider) than Scroll View, a scrollbar appears.
Content View can not only be a single view, but also multiple views, as long as they are appropriately constrained using alignment and size constraints to Scroll View.
For details, you may follow this article: Link.

How to vertically align two UILabels within one line?

I am trying to put two UILabels within one line: one UILable on left side, with text left-aligned, one UILabel on right side, with text right-aligned. Please see above image. They have different font sizes.
I used below auto layout constraints:
let labelHorizontalConstrains = NSLayoutConstraint.constraints(
withVisualFormat: "H:|-20-[nameLabel]-15-[birthDeathDateLabel]-20-|",
metrics: nil,
views: views)
allConstraints += labelHorizontalConstrains
But the result shows that they are not vertically aligned: The left UILabel is lower than the right UILabel. How to fix this?
You need to add a centerYAnchor constraint.
birthDeathDateLabel.centerYAnchor.constraint(equalTo: nameLabel.centerYAnchor).isActive = true
However, if you want it aligned with the base of the text, you should use a UIStackView.
let stackView = UIStackView(arrangedSubviews: [nameLabel, birthDeathDateLabel])
stackView.alignment = .firstBaseline
stackView.axis = .horizontal
// Add other stackview properties and constraints
you need to add a leading constraint and a height constraint to the right label. add a trailing and height constraint to the left label. then specify an equal widths constraint. also on the right label add the distance from the left label with a trailing constraint and for the left label add a leading constraint how far you want it from the right label.. much easier on storyboard. you could also use fit equally.. I can't remember the actual code, but it might have refreshed your memory. if I was too add that sort of constraint I would do it on a skeleton storyboard.

UIStackView Spacing - Don't push to top and bottom anchors

I am trying to distribute some nested stack views and I think I'm missing a property to help me align the various views the way I want them.
Here's the current output:
The issue with this is that the two arranged subviews that are added to each column (a stackview), are distributed so that the first subview aligns to the top, and the second subview aligns to the bottom (leaving a variable space in between them).
But here's what I am hoping for - always a fixed space (say 10 px) in between the first and second arranged subview in each column, and the extra space below the second arranged subview is just left to be what it needs to be.
The view is arranged as follows:
outerStackView = the green view: (20px off top, 64px off left, 20px off bottom,
64px off right - present in both screenshots but only highlighted on the top one) with properties:
outerStackView.axis = .Horizontal
outerStackView.distribution = .FillEqually
outerStackView.spacing = 10
leftStackView, middleStackView, rightStackView added to the outerStackView each with properties:
columnStackView.axis = .Vertical
columnStackView.distribution = .Fill
columnStackView.alignment = UIStackViewAlignment.Top
columnStackView.spacing = 10
Then each column has 2 stackViews inside of it, represented by the darker gray box directly around the red and blue boxes. With properties:
redBlueStackView.axis = .Horizontal
redBlueStackView.distribution = .FillProportionally
redBlueStackView.alignment = UIStackViewAlignment.Top
redBlueStackView.spacing = 4
You should pin your stack view to you containing view. That will give you a more consistent look. You can also best all three of your stack view in a horizontal stack view them selves if you want all 3 to be equal sizing. Another tip is to mess with the content hugging priority and compression resistance variables. Hope that helps let me know if you have more questions.

How do I control the relative widths of UIStackViews nested within another stack view?

I've a fairly difficult layout design that might be easier using nested stack views in iOS. BUT, I'm having problems controlling the size or distribution of stacks nested inside other stacks. One part of the layout, for example, looks OK-ish if I set Distribution to Fit Equally:
BUT, what I really want is the photo and container to be about 1/3 the width of the text field stack. If I set Distribution to Fit Proportionally, the stack with the image (which doesn't change size) and container spreadout and squash the text against the side of the display. Everything I read suggests to reduce the Content Compression Resistance Priority. I've tried this on the image, the container and on the stack view itself, but it doesn't do much.
Could someone please point me in the right direction to control the relative widths of stacks nested inside other stacks?
To answer your question: Could someone please point me in the right direction to control the relative widths of stacks nested inside other stacks?
...
The problem is that your top-level UIStackView is asking for the intrinsicContentSize of all its subviews when determining how to divy up extra space/squash things together, based on each of the subviews' returned intrinsicContentSize and their contentHuggingPriority/contentCompressionResistance. Unfortunately, UIStackView itself - ie your nested UIStackView - doesn't return anything useful for its own intrinsicContentSize (despite it having its own subviews, which do). So the top-level UIStackView just ploughs ahead and lays things out as though the nested one doesn't care, which is why your nested UIStackView is ending up wider than you'd like.
I've had good luck by using a simple UIStackView subclass for the nested one which returns a useful intrinsicContentSize based on its own contents' widths (for a vertical axis) or heights (for a horizonal axis), as follows:
#implementation NestedStackView
- (CGSize)intrinsicContentSize
{
CGSize size = [super intrinsicContentSize]; // returns {UIViewNoIntrinsicMetric,UIViewNoIntrinsicMetric}
for (UIView *view in self.arrangedSubviews)
if (!view.hidden) { // UIStackView ignores hidden subviews when doing its layout; so should we...
if (self.axis == UILayoutConstraintAxisVertical) {
size.width = MAX(view.intrinsicContentSize.width, size.width);
} else {
size.height = MAX(view.intrinsicContentSize.height, size.height);
}
}
return size;
}
#end
By doing so, the top-level UIStackView now takes the nested UIStackView's desired content width into account when allocating its space. [aside: I first attempted adding an explicit NSLayoutConstraint on the width of the nested UIStackView, but it was just ignored. Whereas returning an instrinsicContentSize.width worked]
I'd hope there might be a better answer, but the only effective method that I've found is to put the image into a view and pin it to the view's edges. The size of the view can then be controlled with constraints.
If anyone has a better approach, they can still answer as part of this more detailed question:
https://stackoverflow.com/questions/33875801/how-to-position-and-size-images-and-their-frames-in-nested-stack-views-in-ib-w
One easy way to do this is to use AutoLayout to set relative width constraints on your nested stack views. For example, if you want to have your left UIStackView to fill 2/3rds of the screen and your right UIStackViewto fill 1/3rd, you can use the code below.
let leftStackView = UIStackView(arrangedSubviews: [...])
leftStackView.axis = .vertical
let rightStackView = UIStackView(arrangedSubviews: [...])
rightStackView.axis = .vertical
let containerStackView = UIStackView(arrangedSubviews:
[leftStackView, rightStackView])
containerStackView.axis = .horizontal
containerStackView.distribution = .fillProportionally
containerStackView.translatesAutoresizingMaskIntoConstraints = false
addSubview(containerStackView)
//leftStackView will be twice as wide as the rightStackView, so
//the distribution is 2/3rds to 1/3rd
leftStackView.widthAnchor.constraint(equalTo:
rightStackView.widthAnchor, multiplier: 2.0).isActive = true

How to add leading padding to view added inside an UIStackView

This is my setup: I have an UIScrollView with leading,top, trialing edge set to 0. Inside this I add an UIStackView with this constraints:
stackView.centerYAnchor.constraintEqualToAnchor(selectedContactsScrollView.centerYAnchor).active = true
stackView.leadingAnchor.constraintEqualToAnchor(selectedContactsScrollView.leadingAnchor).active = true
Inside the stack view I add some views.
My issue is that because of the constraints the first view added to stack view will also have leading edge = 0.
What are the ways that I could add some padding to the first view ? Without adjusting the scroll view constraints.
When isLayoutMarginsRelativeArrangement property is true, the stack view will layout its arranged views relative to its layout margins.
stackView.layoutMargins = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
stackView.isLayoutMarginsRelativeArrangement = true
But it affects all arranged views inside to the stack view. If you want this padding for only one arranged view, you need to use nested UIStackView
I have found that constraints don't work inside a Stack View, or they seem somewhat strange.
(Such as if I add leading/trailing constraint to selected on image stackview, that adds leading to collectionview too, but doesn't add trailing; and it be conflict for sure).
To set layout margins for all views inside the stackview, select:
Stack View > Size Inspector > Layout Margins > Fixed
Note: "Fixed" option was formerly called "Explicit", as seen in the screenshots.
Then add your padding:
The solution you have provided doesn't add a padding for your views inside your UIStackView (as you wanted in the question), but it adds a leading for the UIStackView.
A solution could be to add another UIStackView inside your original UIStackView and give the leading to this new UIStackVIew. Then, add your views to this new UIStackView.
Hint, you can do that completely using Interface Builder. In other words, no need to write code for it.
What worked for me is to add to stack view another UIView that's just a spacer (works at least with stackView.distribution = .Fill):
let spacerView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
stackView.addArrangedSubview(spacerView)
stackView.addArrangedSubview(viewThatNeedsSpaceBeforeIt)
stackView.addArrangedSubview(NextView)...
If you only need leading padding, then you can set the stack view's Alignment to "Trailing" and then you will be free to specify unique Leading constraints on each of its contained subviews.
As a bonus, you can also set the stack view's alignment to "Center" and then you can use Leading and/or Trailing constraints to give each item its own padding on both sides.
Set your stackview alignment to "center". After that you can give every subview different leading and trailing.
swift 3:
You just need set offset by:
firstView.leadingAnchor.constraint(equalTo: parentView.leadingAnchor, constant: 200).isActive = true
Be sure this constraint set after you parentView.addArrangdSubView(firstView)
The solution would be to have a regular view in the stack view to hold whatever views you are wanting to add constraints to, and then you can add constraints for your items that are relative to the views in the stack view. That way, your original views can have leading and trailing constraints within the stack view.
This can be done in the interface builder and programatically.
This question already has good answers,
One suggestion though, use spacing property to set the spacing between the views. For first and last views there can be two options, either set insets as #tolpp suggested or add constraint attaching to parent (stackview) with constant to add padding.
What we did was add transparent components (e.g., UIButton/UIView) as the first and last children of the UIStackView. Then set constrain the width of these invisible children to adjust the padding.
It seems that the solution was pretty simple. Instead of:
stackView.leadingAnchor.constraintEqualToAnchor(selectedContactsScrollView.leadingAnchor).active = true
I just wrote:
stackView.leadingAnchor.constraintEqualToAnchor(selectedContactsScrollView.leadingAnchor, constant: 15).active = true
Just add an empty view at the beginning of the stack view (also constraining its width and/or height):
stackView.insertArrangedSubview(UIView().constrain(width: 0, height: 0), at: 0)
and/or at the end:
stackView.addArrangedSubview(UIView().constrain(width: 0, height: 0))
I created this simple UIView extension to add the constraints:
extension UIView {
func constrain(width: CGFloat, height: CGFloat) -> Self {
NSLayoutConstraint.activate([
widthAnchor.constraint(equalToConstant: width),
heightAnchor.constraint(equalToConstant: height)
])
return self
}
}

Resources