Center stack view elements and not fill them - ios

I am using a UIStackView as UITableView's BackGroundView property so when there was an error getting the collection that populates the tableView I can call a function that displays this stack view containing views that show a warning message and a retry button.
I tested doing a similar behaviour in an empty UIViewController so I could center the stackView and its children. The solution worked when I pinned the stack view to the superView's trailing and leading, centered it vertically and set it's top anchor to be greater or equal to the superView's top anchor and similarly it's bottom anchor is greater or equal to the superView's bottom anchor. I have also set the alignment to center and distribution to fill and all seemed to work properly.
Here are some screenshots:
I used this code in a UITableView's extension, but could only reproduce this behaviour. Are there any errors on this code?
func show(error: Bool, withMessage message : String? = nil, andRetryAction retry: (() -> Void)? = nil){
if error{
let iconLabel = UILabel()
iconLabel.GMDIcon = .gmdErrorOutline
iconLabel.textAlignment = .center
iconLabel.numberOfLines = 0
iconLabel.font = iconLabel.font.withSize(50)
iconLabel.textColor = Constants.Colors.ErrorColor
iconLabel.backgroundColor = .blue
let messageLabel = UILabel()
messageLabel.text = message ?? "Ocorreu um erro"
messageLabel.textColor = Constants.Colors.ErrorColor
messageLabel.numberOfLines = 0
messageLabel.textAlignment = .center
messageLabel.font = UIFont(name: "TrebuchetMS", size: 20)
messageLabel.backgroundColor = .green
var views: [UIView] = [iconLabel, messageLabel]
if let retry = retry{
let button = RaisedButton(title: "Tentar novamente")
button.pulseColor = Constants.Colors.PrimaryTextColor
button.backgroundColor = Constants.Colors.PrimaryColor
button.titleColor = .white
button.actionHandle(controlEvents: .touchUpInside, ForAction: retry)
button.contentEdgeInsets = UIEdgeInsetsMake(10,10,10,10)
views.append(button)
}
}else{
self.backgroundView = nil
}
}
let stack = UIStackView()
stack.spacing = 10
stack.axis = .vertical
stack.alignment = .center
stack.distribution = .fill
stack.translatesAutoresizingMaskIntoConstraints = false
for view in views{
view.translatesAutoresizingMaskIntoConstraints = false
stack.addArrangedSubview(view)
}
if self.tableFooterView == nil{
tableFooterView = UIView()
}
self.backgroundView = stack;
if #available(iOS 11, *) {
let guide = self.safeAreaLayoutGuide
stack.topAnchor.constraint(greaterThanOrEqualTo: guide.topAnchor).isActive = true
stack.bottomAnchor.constraint(greaterThanOrEqualTo: guide.bottomAnchor).isActive = true
stack.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true
stack.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true
stack.centerYAnchor.constraint(equalTo: guide.centerYAnchor).isActive = true
} else {
stack.topAnchor.constraint(greaterThanOrEqualTo: self.topAnchor).isActive = true
stack.bottomAnchor.constraint(greaterThanOrEqualTo: self.bottomAnchor).isActive = true
stack.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
stack.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
stack.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
}

A stack view knows its height if its elements all have an intrinsic size (ie its the sum of their individual heights + the inter item spacing). In this case because you have a 2 y position constraints, you are implying a height, so your constraints are unsatisfiable. The only y axis constraint you need is center vertically. get rid of the top and bottom constraints. The system will then use the intrinsic size to compute the height of the stack view and center it vertically in the background view. Leave your x axis constraints as is.

Related

UIStackView alignment issue

I want to achieve this requirement
if vertical stack has two label than Text should be centre aligned to image
and if not than top aligned to Image
How can I achieve this without writing any code
You'll need to control the alignment of the outer (i.e final stack view which contains both the image and the labels' stack view) stack view.
As you will need to control which labels need to be added to the labels' stack view, I assume you will be doing this programmatically. So basically you'll need:
finalStackView.alignment = labelsStackView.arrangedSubviews.count > 2 ? .top : .center
Here is a complete example which produces the below outputs:
class ViewController: UIViewController {
let finalStackView = UIStackView()
override func viewDidLoad() {
super.viewDidLoad()
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.heightAnchor.constraint(equalToConstant: 200).isActive = true
imageView.widthAnchor.constraint(equalToConstant: 200).isActive = true
imageView.image = #imageLiteral(resourceName: "taylor-swift")
let label1 = UILabel()
let label2 = UILabel()
let label3 = UILabel()
let label4 = UILabel()
label1.translatesAutoresizingMaskIntoConstraints = false
label2.translatesAutoresizingMaskIntoConstraints = false
label3.translatesAutoresizingMaskIntoConstraints = false
label4.translatesAutoresizingMaskIntoConstraints = false
label1.text = "Hello"
label2.text = "72 mins"
label3.text = "Hello 3"
label4.text = "Hello 4"
let labelsStackView = UIStackView(arrangedSubviews: [label1, label2, label3, label4])
labelsStackView.translatesAutoresizingMaskIntoConstraints = false
labelsStackView.axis = .vertical
labelsStackView.distribution = .fill
labelsStackView.alignment = .leading
finalStackView.addArrangedSubview(imageView)
finalStackView.addArrangedSubview(labelsStackView)
finalStackView.axis = .horizontal
finalStackView.distribution = .fill
finalStackView.alignment = labelsStackView.arrangedSubviews.count > 2 ? .top : .center
view.addSubview(finalStackView)
finalStackView.translatesAutoresizingMaskIntoConstraints = false
finalStackView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
finalStackView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
finalStackView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}
}
With the exact code above the output is:
With 2 labels added to the labelsStackView, the output is:
Keep the labels vertical stackview in a Horizontal stackView.
if you have more than 2 labels, change Horizontal stackView alignment to top else keep it to center.
Your layout structure be like
> main stack view (Horizontal)
> Image
> stack view (Horizontal)
>labels stack view (Vertical)
> Labels

in nested UIStackView when I add more than one arranged subview, it breaks the layout, why?

Playing with UIStackView I encountered a weird issue which does not allow me to add extra arranged subview in nested UIStackView:
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
let subViews = [UIColor.gray, UIColor.darkGray, UIColor.lightGray].map { (color) -> UIView in
let v = UIView()
v.backgroundColor = color
return v
}
let redView = UIStackView(arrangedSubviews: subViews)
redView.distribution = .fillEqually
redView.heightAnchor.constraint(lessThanOrEqualToConstant: 100).isActive = true
let blueView = UIView()
blueView.backgroundColor = .blue
let buttons = [UIColor.gray, UIColor.darkGray, UIColor.lightGray].map { (color) -> UIView in
let v = UIView()
v.backgroundColor = color
return v
}
let buttonsView = UIStackView(arrangedSubviews: buttons)
buttonsView.distribution = .fillEqually
buttonsView.heightAnchor.constraint(lessThanOrEqualToConstant: 100).isActive = true
let stackView = UIStackView(arrangedSubviews: [redView, blueView, buttonsView])
view.addSubview(stackView)
stackView.axis = .vertical
stackView.fillSuperview()
}
In result, I get full-stretched blue view instead of expecting behavior:
But when I leaving ONE subview in bottom stack view - it appears as expected
let buttons = [UIColor.gray].map { (color) -> UIView in
let v = UIView()
v.backgroundColor = color
return v
}
let buttonsView = UIStackView(arrangedSubviews: buttons)
buttonsView.distribution = .fillEqually
buttonsView.heightAnchor.constraint(lessThanOrEqualToConstant: 100).isActive = true
let stackView = UIStackView(arrangedSubviews: [redView, blueView, buttonsView])
why ? What is wrong with the code ? Any help or hint is appreciated, I tried translatesAutoresizingMaskIntoConstraints = false on top and bottom stack views as well but without any luck
on the bottom stackview it was required to set
buttonView.heightAnchor.constraint(equalToConstant: 100).isActive = true
instead of
buttonView.heightAnchor.constraint(lessThanOrEqualToConstant: 100).isActive = true

UIStackView container view height based on subviews

Here is my simple example. I have 1 vertical stack view with 1 subview. I want that subviews height to be based on the intrinsic height of the label within it, so that I can maintain a dynamic height for the entire stack view. How can this be done? Thanks
I think you did it right. But here is the keys:
Don't set height for stackView.
Set label top, bottom, left, trailing constraint to view.
Run. It should be okay on simulator.
If you found label's height seems not wrapping (neither both on storyboard or simulator), then change label's Vertical Content Hugging Priority to 750.
Try this code:
class DyanmicTextLabelViewController: UIViewController {
private var didAddConstraint = false
private let label: UILabel = {
let view = UILabel()
view.translatesAutoresizingMaskIntoConstraints = false
view.setContentHuggingPriority(.required, for: .vertical)
view.setContentCompressionResistancePriority(.required, for: .vertical)
view.text = "Layout anchors let you create constraints in an easy-to-read, compact format. They expose a number of methods for creating different types of constraints, as shown in Listing 13-1."
view.numberOfLines = 0
return view
}()
private lazy var container: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(label)
view.backgroundColor = .red
return view
}()
private lazy var stackview : UIStackView = {
let view = UIStackView()
view.translatesAutoresizingMaskIntoConstraints = false
view.axis = .horizontal
view.distribution = .fill
view.addArrangedSubview(container)
return view
}()
override func loadView() {
super.loadView()
view.addSubview(stackview)
view.setNeedsUpdateConstraints()
view.backgroundColor = .white
}
override func updateViewConstraints() {
super.updateViewConstraints()
if didAddConstraint == false {
didAddConstraint = true
// stackview constraints
stackview.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
let topAnchor = stackview.topAnchor.constraint(equalTo: view.topAnchor)
topAnchor.constant = 20
topAnchor.isActive = true
stackview.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
// label constraint
// example for giving label a left padding
let labelLeft = label.leftAnchor.constraint(equalTo: container.leftAnchor)
labelLeft.constant = 16.0
labelLeft.isActive = true
label.topAnchor.constraint(equalTo: container.topAnchor).isActive = true
label.rightAnchor.constraint(equalTo: container.rightAnchor).isActive = true
label.bottomAnchor.constraint(equalTo: container.bottomAnchor).isActive = true
}
}
}
The important part here is the initialization of stackview, label & constraint set on label
label initialization
private let label: UILabel = {
let view = UILabel()
view.translatesAutoresizingMaskIntoConstraints = false
view.setContentHuggingPriority(.required, for: .vertical)
view.setContentCompressionResistancePriority(.required, for: .vertical)
view.text = "Layout anchors let you create constraints in an easy-to-read, compact format. They expose a number of methods for creating different types of constraints, as shown in Listing 13-1."
view.numberOfLines = 0
return view
}()
stackview initialization
private lazy var stackview : UIStackView = {
let view = UIStackView()
view.translatesAutoresizingMaskIntoConstraints = false
view.axis = .horizontal
view.distribution = .fill
view.addArrangedSubview(container)
return view
}()
label constraint
// label constraint
// example for giving label a left padding
let labelLeft = label.leftAnchor.constraint(equalTo: container.leftAnchor)
labelLeft.constant = 16.0
labelLeft.isActive = true
label.topAnchor.constraint(equalTo: container.topAnchor).isActive = true
label.rightAnchor.constraint(equalTo: container.rightAnchor).isActive = true
label.bottomAnchor.constraint(equalTo: container.bottomAnchor).isActive = true
This settings could be easily translated to storyboard.

Choose which subview on a stackView will stretch (Programmatically)

I have a display of horizontal stack views, which subviews consists on a label and a textField. the stackView is constrained with the borders of the view
I'm trying to stretch my textField subview to so it fills the remaining space of the stack, while the label's stacks adjusts to fit the label size itself. But the inverse is happening. I've tried many solutions but nothing helped me. All the views and constraints we're made programmatically.
For my stack, I'm using:
func customTextField() -> UIStackView {
let stack: UIStackView = {
let sv = UIStackView()
sv.axis = .horizontal
sv.isLayoutMarginsRelativeArrangement = true
sv.alignment = .leading
sv.backgroundColor = .red
sv.translatesAutoresizingMaskIntoConstraints = false
return sv
}()
let label: UILabel = {
let lb = UILabel()
lb.backgroundColor = .red
lb.text = "Label is here"
lb.translatesAutoresizingMaskIntoConstraints = false
return lb
}()
let textField: UITextField = {
let tf = UITextField()
tf.backgroundColor = .blue
tf.text = "Text Field"
tf.translatesAutoresizingMaskIntoConstraints = false
return tf
}()
stack.addArrangedSubview(label)
stack.addArrangedSubview(textField)
return stack
}
the caller of my customTextField:
let profileUserStack: UIStackView = {
let stack = UIStackView()
stack.axis = .vertical
stack.spacing = 8
stack.contentMode = .scaleToFill
stack.translatesAutoresizingMaskIntoConstraints = false
return stack
}()
self.addSubview(profileUserStack)
for i in profileTextViews {
let view = self.customTextField()
profileUserStack.addArrangedSubview(view)
}
constraints.append(profileUserStack.buildConstraint(toItem: perfilImageView, constant: 32, type: .top, baseItem: .bottom))
constraints.append(profileUserStack.buildConstraint(toItem: self, constant: 16, type: .leading, baseItem: .leading))
constraints.append(profileUserStack.buildConstraint(toItem: self, constant: -16, type: .trailing, baseItem: .trailing))
activateConstraints(&constraints, to: self)
The results:
https://imgur.com/a/ccFZlRM
Notice that's exactly what I want to achieve. But I want the textField to be stretched.
Set contentHuggingPriority to your label such that it always stays as the size of its content and textField takes remaining space.
label.setContentHuggingPriority(.defaultHigh, for: .horizontal)

UIStackview with differently aligned subviews

I'd like to align the Blue and Purple views to the center of the screen, and I'd like to align the green view to the left of the screen:
Here is my code:
view.backgroundColor = UIColor.orangeColor()
//Stackview:
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(stackView)
stackView.topAnchor.constraintEqualToAnchor(self.view.topAnchor).active = true
stackView.leftAnchor.constraintEqualToAnchor(self.view.leftAnchor).active = true
stackView.rightAnchor.constraintEqualToAnchor(self.view.rightAnchor).active = true
stackView.axis = UILayoutConstraintAxis.Vertical
stackView.alignment = .Center
//Blue view:
let blueBox = UIView()
stackView.addArrangedSubview(blueBox)
blueBox.backgroundColor = UIColor.blueColor()
blueBox.heightAnchor.constraintEqualToConstant(140).active = true
blueBox.widthAnchor.constraintEqualToConstant(140).active = true
//Inner stackview that contains the green view:
let greenBoxContainer = UIStackView()
let greenBox = UIView()
stackView.addArrangedSubview(greenBoxContainer)
greenBoxContainer.addArrangedSubview(greenBox)
greenBoxContainer.alignment = .Leading
//Green view:
greenBox.backgroundColor = UIColor.greenColor()
greenBox.widthAnchor.constraintEqualToConstant(120).active = true
greenBox.heightAnchor.constraintEqualToConstant(120).active = true
//Purple view:
let purpleView = UIView()
stackView.addArrangedSubview(purpleView)
purpleView.backgroundColor = UIColor.purpleColor()
purpleView.heightAnchor.constraintEqualToConstant(50.0).active = true
purpleView.widthAnchor.constraintEqualToConstant(50.0).active = true
To repeat, how can I align the left edge of the green view with the left edge of the screen?
I tried this:
greenBoxContainer.widthAnchor.constraintEqualToAnchor(stackView.widthAnchor).active = true
but it only stretches the green view through the length of the screen.
One way is to add a spacer view:
let greenBox = UIView()
stackView.addArrangedSubview(greenBoxContainer)
greenBoxContainer.addArrangedSubview(greenBox)
let spacer = UIView()
greenBoxContainer.addArrangedSubview(spacer)
spacer.rightAnchor.constraintEqualToAnchor(greenBoxContainer.rightAnchor).active = true
greenBoxContainer.widthAnchor.constraintEqualToAnchor(stackView.widthAnchor).active = true
greenBox.backgroundColor = UIColor.greenColor()
greenBox.widthAnchor.constraintEqualToConstant(120).active = true
greenBox.heightAnchor.constraintEqualToConstant(120).active = true
Note that I'm no longer setting greenBoxContainer's alignment, so it defaults to .Fill. Thus the right edge of spacer is flushed to the inner stackview's right edge, and it takes up all the width, leaving greenBox just enough room to satisfy its width constraint.
But this is a workaround, I'd like to be able to specify alignments without having to create spacer views..

Resources