Horizontal Stackview left align items - swift

I am creating a horizontal UIStackView and want to left align items in it.
Here is my code:
let nameLabel: UILabel = {
let label=UILabel()
label.text = "First Name:"
label.textColor = UIColor.black
label.font = UIFont.systemFont(ofSize: 20)
label.textAlignment = .left
label.translatesAutoresizingMaskIntoConstraints=false
return label
}()
let nameTextField: UITextField = {
let label=UITextField()
label.placeholder = "Enter Name"
label.textColor = UIColor.darkGray
label.font = UIFont.systemFont(ofSize: 18)
label.textAlignment = .left
label.isUserInteractionEnabled = false
label.translatesAutoresizingMaskIntoConstraints=false
return label
}()
lazy var firstNameView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [self.nameLabel, self.nameTextField])
stackView.translatesAutoresizingMaskIntoConstraints = false;
stackView.axis = .horizontal
stackView.distribution = .fill
stackView.alignment = .center
stackView.spacing = 10.0
return stackView
}()
And here is how i add it to the view
self.view.addSubview(firstNameView)
firstNameView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true;
firstNameView.topAnchor.constraint(equalTo: idLabel.bottomAnchor).isActive = true;
firstNameView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
firstNameView.heightAnchor.constraint(equalToConstant: 40.0).isActive = true
I also tried the following:
firstNameView.trailingAnchor.constraint(greaterThanOrEqualTo: self.view.trailingAnchor).isActive = true
PS: This question is different from UIStackview align left as i am talking about horizontal stackview
According to this link Left aligned horizontal stackview and top aligned vertical stackview
Is there any alternative, i don't really want to set a fixed width.

Wrap your labels in UIViews and pin the labels to the left of these views. Put the views into the stack view and they will fill the stack view without manipulating the labels.

Related

How to make vertical labels bar in Swift?

I would like to make such layout via swift:
I tried to make it in such way:
var buttonArray = [UILabel]()
for (myKey,myValue) in colorDictionary{
buttonArray += [colorButton(withColor: myValue, title: myKey)]
}
let horizontalStack = UIStackView(arrangedSubviews: buttonArray)
horizontalStack.axis = .horizontal
horizontalStack.distribution = .fillEqually
horizontalStack.alignment = .fill
horizontalStack.translatesAutoresizingMaskIntoConstraints = false
horizontalStack.transform = CGAffineTransform(rotationAngle: -CGFloat.pi / 2)
let label2 = UILabel()
label2.text = "Label"
label2.backgroundColor = .red
label2.textColor = .white
label2.textAlignment = .center
label2.lineBreakMode = .byCharWrapping
label2.numberOfLines = 0
label2.translatesAutoresizingMaskIntoConstraints = false
label2.transform = CGAffineTransform(rotationAngle: -CGFloat.pi / 2)
let mainStackView = UIStackView()
mainStackView.axis = .horizontal
mainStackView.translatesAutoresizingMaskIntoConstraints = false
mainStackView.addArrangedSubview(label2)
mainStackView.addArrangedSubview(horizontalStack)
mainContainer.addSubview(mainStackView)
NSLayoutConstraint.activate([
mainStackView.topAnchor.constraint(equalTo: mainContainer.topAnchor, constant: 5),
mainStackView.leftAnchor.constraint(equalTo: mainContainer.leftAnchor,
constant: 20),
mainStackView.rightAnchor.constraint(equalTo: mainContainer.rightAnchor,
constant: -20),
mainStackView.heightAnchor.constraint(equalToConstant: 270),
])
where colorButton is:
func colorButton(withColor color:UIColor, title:String) -> UILabel{
let newButton = UILabel()
newButton.backgroundColor = color
newButton.text = title
newButton.textAlignment = .center
newButton.textColor = UIColor.white
return newButton
}
and here is the result which I got:
How I can make all these labels look like the desired image? And also I'm not sure whether label rotation can be done by my method.
What I would do is first get it working without any transformations so it appears as a normal, not rotated setup. Once that is working, you only need to apply a single transformation to the main stack view to get the whole thing rotated. Then finally you can tweak the constraints to get it positioned correctly.
Here is code that works:
let horizontalStack = UIStackView(arrangedSubviews: buttonArray)
horizontalStack.axis = .horizontal
horizontalStack.distribution = .fillEqually
horizontalStack.alignment = .fill
horizontalStack.translatesAutoresizingMaskIntoConstraints = false
let label2 = UILabel()
label2.text = "Label"
label2.backgroundColor = .red
label2.textColor = .white
label2.textAlignment = .center
label2.lineBreakMode = .byCharWrapping
label2.numberOfLines = 0
label2.translatesAutoresizingMaskIntoConstraints = false
let mainStackView = UIStackView()
mainStackView.axis = .vertical
mainStackView.distribution = .equalSpacing
mainStackView.translatesAutoresizingMaskIntoConstraints = false
mainStackView.addArrangedSubview(label2)
mainStackView.addArrangedSubview(horizontalStack)
mainStackView.transform = CGAffineTransform(rotationAngle: -CGFloat.pi / 2)
mainContainer.addSubview(mainStackView)
NSLayoutConstraint.activate([
mainStackView.centerYAnchor.constraint(equalTo: mainContainer.centerYAnchor),
mainStackView.centerXAnchor.constraint(equalTo: mainContainer.leftAnchor, constant: 40),
// Set the "width", not the "height"
mainStackView.widthAnchor.constraint(equalToConstant: 270),
])
Changes:
I removed the transformation you had for the horizontal stack view and the big label.
I added a single transformation to the main stack view.
I used a vertical, not horizontal, stack view for the main stack.
Updated the properties of the main stack view so the main label fills the area above the other labels.
Updated the constraints. Adjust those to suit your needs.
Note that you need to set the width of the main stack view since the constraint is relative to the untransformed main stack view.

Displaying property with Horizontal and Vertical Stack View in Swift

I am new to swift . I am following the programmatic approach to create the view . I created two stack view . One is horizontal and other one is vertical. Into horizontal stack view I want to display the label property and Vertical stack view I want to display the Image. I want to display the image on left side and label properties on right side.
Here is the code I used ..
import UIKit
class PeopleCell: UITableViewCell {
static let identifier = "PeopleCell"
private lazy var mainStackView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.distribution = .fill
stackView.alignment = .leading
return stackView
}()
private lazy var stackView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .horizontal
stackView.distribution = .fill
stackView.alignment = .center
return stackView
}()
private lazy var lastnameTitleLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
label.textAlignment = .center
return label
}()
private lazy var firstnameTitleLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
label.textAlignment = .center
return label
}()
private lazy var peopleImageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
// imageView.backgroundColor = .blue
return imageView
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setUpUI()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configureCell(firstName: String, lastName: String) {
firstnameTitleLabel.text = "Firstname :\(firstName)"
lastnameTitleLabel.text = "Lastname : \(lastName)"
}
func configureImageCell(row: Int, viewModel: ViewModel) {
peopleImageView.image = nil
viewModel
.downloadImage(row: row) { [weak self] data in
let image = UIImage(data: data)
self?.peopleImageView.image = image
}
}
private func setUpUI() {
stackView.addArrangedSubview(lastnameTitleLabel)
stackView.addArrangedSubview(firstnameTitleLabel)
mainStackView.addArrangedSubview(peopleImageView)
mainStackView.addArrangedSubview(stackView)
contentView.addSubview(mainStackView)
// constraints
let safeArea = contentView.safeAreaLayoutGuide
mainStackView.topAnchor.constraint(equalTo: safeArea.topAnchor).isActive = true
mainStackView.bottomAnchor.constraint(equalTo: safeArea.bottomAnchor).isActive = true
mainStackView.leadingAnchor.constraint(equalTo: safeArea.leadingAnchor, constant: 10).isActive = true
mainStackView.trailingAnchor.constraint(equalTo: safeArea.trailingAnchor, constant: -10).isActive = true
peopleImageView.heightAnchor.constraint(equalToConstant: 140).isActive = true
peopleImageView.widthAnchor.constraint(equalToConstant: 140).isActive = true
stackView.leadingAnchor.constraint(equalTo: mainStackView.leadingAnchor).isActive = true
stackView.trailingAnchor.constraint(equalTo: mainStackView.trailingAnchor).isActive = true
}
}
Here is the screenshot ..
Here is the expected result.
The main problem is that you have your .axis properties reversed.
You want your mainStackView.axis to be .horizontal and your stackView.axis to be .vertical.
Also, these two lines are not needed (and cause problems):
// don't do this
//stackView.leadingAnchor.constraint(equalTo: mainStackView.leadingAnchor).isActive = true
//stackView.trailingAnchor.constraint(equalTo: mainStackView.trailingAnchor).isActive = true
As a side note, instead of:
let safeArea = contentView.safeAreaLayoutGuide
you may want to use:
let safeArea = contentView.layoutMarginsGuide
which gives you the default cell margins.
Edit
// this is the "main" stack view with
// the image on the left
// the labels on the right
// so it needs to be HORIZONTAL
private lazy var mainStackView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
//stackView.axis = .vertical
stackView.axis = .horizontal
stackView.distribution = .fill
return stackView
}()
// this is the "labels" stack view with
// two (or more) labels from top down
// so it needs to be VERTICAL
private lazy var stackView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
//stackView.axis = .horizontal
stackView.axis = .vertical
stackView.distribution = .fill
return stackView
}()

StackView with two labels doesn't wrap content

I have one StackView with two labels inside. I want to place the two labels one next to the other.
private lazy var stackView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.alignment = .center
stackView.axis = .horizontal
stackView.backgroundColor = .black
stackView.spacing = 10
return stackView
}()
// MARK: Labels
private lazy var firstLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
label.textColor = UIColor.brandColor(.white)
label.textAlignment = .right
label.font = UIFont.bloomSpeakFont(.titleUltraHeavy, ofSize: 8.0)
return label
}()
private lazy var secondLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
label.textColor = UIColor.brandColor(.white)
label.textAlignment = .right
label.font = UIFont.bloomSpeakFont(.bodyExtraBold, ofSize: 10.0)
return label
}()
// MARK: - Setup
private func setupStackView() {
stackView.addArrangedSubview(firstLabel)
//firstLabel.widthAnchor.constraint(equalToConstant: 100).isActive = true
//firstLabel.heightAnchor.constraint(equalToConstant: 100).isActive = true
//firstLabel.setContentHuggingPriority(UILayoutPriority.defaultLow, for: .horizontal)
stackView.addArrangedSubview(secondLabel)
//secondLabel.widthAnchor.constraint(equalToConstant: 100).isActive = true
//secondLabel.heightAnchor.constraint(equalToConstant: 100).isActive = true
//secondLabel.setContentHuggingPriority(UILayoutPriority.defaultHigh, for: .horizontal)
addSubview(stackView)
stackView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
stackView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
}
My problem is:
What I want:
The label next to the number and also some padding some padding with the margins.
Thanks in advance.
EDIT
After set spacing to 0, numberOfLines to 1, stackView.alignment = .fill I got the result bellow. I just wonder how to add padding to the labels?
Thanks to the comments of #SandeepBhandari and #DonMag i could solved my issue:
The final solution was:
private lazy var stackView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.alignment = .fill // << changed from .center to .fill
stackView.axis = .horizontal
stackView.backgroundColor = .black
//stackView.spacing = 10 << removed line
return stackView
}()
// MARK: Labels
private lazy var firstLabel: PaddingLabel = {
let label = PaddingLabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 1 // << changed from 0 to 1
label.textColor = UIColor.brandColor(.white)
label.textAlignment = .right
label.font = UIFont.bloomSpeakFont(.titleUltraHeavy, ofSize: 8.0)
return label
}()
private lazy var secondLabel: PaddingLabel = {
let label = PaddingLabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 1
label.textColor = UIColor.brandColor(.white)
label.textAlignment = .right
label.font = UIFont.bloomSpeakFont(.bodyExtraBold, ofSize: 10.0)
return label
}()
// MARK: - Setup
private func setupStackView() {
stackView.addArrangedSubview(firstLabel)
stackView.addArrangedSubview(secondLabel)
firstLabel.paddingLeft = 2
firstLabel.paddingRight = 1
secondLabel.paddingLeft = 1
secondLabel.paddingRight = 2
addSubview(stackView)
stackView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
stackView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
}
I also use this guide https://johncodeos.com/how-to-add-padding-in-uilabel-in-ios-using-swift/, to add padding to the labels.
The final result is:

Is it possible to add constraint between two UILabels?

Yeah basically i want to create a constraint between the bottom border of one UILabel (label1) and top border of another UILabel (label2). I currently have the top of my label 1 connected to the safearea and constant height set up to 100.
let label1 = UILabel.init()
label1.text = "123"
view.addSubview(label1)
label1.translatesAutoresizingMaskIntoConstraints = false
label1.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
label1.heightAnchor.constraint(equalToConstant: 100).isActive = true
let label2 = UILabel.init()
label2.text = "456"
view.addSubview(label2)
label2.translatesAutoresizingMaskIntoConstraints = false
label2.topAnchor.constraint(???)
You need
let label1 = UILabel()
label1.text = "123"
view.addSubview(label1)
label1.translatesAutoresizingMaskIntoConstraints = false
let label2 = UILabel()
label2.text = "456"
view.addSubview(label2)
label2.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
label1.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor,constant:20.0),
label1.centerXAnchor.constraint(equalTo:self.view.centerXAnchor),
label2.topAnchor.constraint(equalTo: self.label1.bottomAnchor,constant:20.0),
label2.centerXAnchor.constraint(equalTo:self.view.centerXAnchor)
])
You can also use a vertical UIStackView
Simply use vertical stackview .
let label1 = UILabel()
label1.text = "123"
let label2 = UILabel()
label2.text = "456"
let stackView = UIStackView(arrangedSubviews: [label1, label2])
stackView.axis = .vertical
stackView.distribution = .equalSpacing
stackView.alignment = .center
stackView.spacing = 10
stackView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
stackView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor,constant:20.0),
stackView.centerXAnchor.constraint(equalTo:self.view.centerXAnchor)
])

Hiding a view inside stackview still keeps constraints active

This code can be copy paste inside a newly created project:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let label = createLabel()
let imageView = createImageView()
let stackView = UIStackView(arrangedSubviews: [imageView, label])
stackView.axis = .vertical
stackView.spacing = 5
view.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { (_) in
imageView.isHidden = true
}
}
func createLabel() -> UILabel {
let label = UILabel(frame: .zero)
label.text = "Some Text"
label.setContentHuggingPriority(.required, for: .horizontal)
label.setContentHuggingPriority(.required, for: .vertical)
label.backgroundColor = .green
return label
}
func createImageView() -> UIImageView {
let imageView = UIImageView()
imageView.backgroundColor = .red
imageView.heightAnchor.constraint(equalToConstant: 200).isActive = true
imageView.heightAnchor.constraint(equalTo: imageView.widthAnchor).isActive = true
return imageView
}
}
It is a UILabel and a UIImageView inside a UIStackView. When I hide the UIImageView, I see that the UIStackView correctly adapts itselfs to the UILabel's height. However, the UIStackView does not adapts itself to the width of the UILabel.
How can I make the UIStackView resize itself to it's only visible views/UILabel? I made a variabele constraint for the UIImageView's height anchor constant and turning that off when hiding the UIImageView, but than the UILabel disappears for some odd reason.
Add stackview alignment
This property determines how the stack view lays out its arranged
views perpendicularly to its axis. The default value is
UIStackView.Alignment.fill.
stackView.alignment = .leading
Stackview resizes itself to it's only visible UILabel
Try changing the Distribution to Fill Equally in the UIStackView's Attribute Inspector and the Alignment to Fill or to center as you like it to be.