UIStackView - why is the stack positioned one on top of the other? - swift

I am trying to get a group of buttons arranged within a stack view. However, when i use a for-each loop to do this, the buttons end up being positioned one on top of the other?
var stackView: UIStackView = {
let sView = UIStackView()
sView.axis = .vertical
sView.distribution = .fill
sView.alignment = .center
return sView
}()
var optionTitles = ["Sign in", "sign out"]
for title in optionTitles{
let btn = UIButton()
btn.setTitle(title, for: .normal)
btn.backgroundColor = optionColour.withAlphaComponent(0.6)
allButtons.append(btn)
stackView.addSubview(btn)
}
// Auto layout constraints
for button in allButtons{
button.translatesAutoresizingMaskIntoConstraints = false
button.heightAnchor.constraint(equalToConstant: optionHeight).isActive = true
button.widthAnchor.constraint(equalTo: stackView.widthAnchor).isActive = true
}
view.addSubview(stackView)
stackTopConstraint = stackView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor)
stackBottomConstraint = stackView.bottomAnchor.constraint(equalTo: view.topAnchor)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
stackTopConstraint!.isActive = true
stackView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true

2 things
1- You need to remove this
button.widthAnchor.constraint(equalTo: stackView.widthAnchor).isActive = true
2- Replace
stackView.addSubview(btn)
with
stackView.addArrangedSubview(btn)

You have:
stackTopConstraint = stackView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor)
stackBottomConstraint = stackView.bottomAnchor.constraint(equalTo: view.topAnchor)
You probably meant view.bottomAnchor in the second line. Surely you don't want to constraint the bottom of the stack view to the top of your view.

Related

Why is my StackView not working? Elements are completely displaced

Hey my StackView is doing nothing, there are two problems:
The first is that the elements on the VC are completely displaced when I turn around the simulator or change the device, so the StackView is not doing what it should do!
The second thing is that the StackView is covering the navigation bar and I don't know how to make it visible.
Can someone help me?
import UIKit
class RegisterViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
let stackView = UIStackView()
var profilePicture = UIButton()
var profileIcon = UIImage()
let usernameTextField = UITextField()
let emailTextField = UITextField()
let passswordTextField = UITextField()
let signInButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.prefersLargeTitles = true
navigationItem.title = "Create an Account"
view.backgroundColor = .white
// SetUp StackView:
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.alignment = .center
stackView.distribution = .fillEqually
stackView.spacing = 50
view.addSubview(stackView)
// SetUp Stack View Constraints:
stackView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20).isActive = true
stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
//Add Elements
stackView.addArrangedSubview(profilePicture)
stackView.addArrangedSubview(usernameTextField)
stackView.addArrangedSubview(passswordTextField)
stackView.addArrangedSubview(signInButton)
// MARK: - Set-Up View-Elements
// SetUp ProfileIcon:
profileIcon = UIImage(named: "characteer")!
profilePicture.setImage(profileIcon, for: .normal)
profilePicture.imageView?.contentMode = .scaleAspectFill
let cornerRadius: CGFloat
cornerRadius = 75 // half of widht/height
profilePicture.layer.cornerRadius = cornerRadius
profilePicture.layer.masksToBounds = true
profilePicture.layer.borderWidth = 1
profilePicture.layer.borderColor = UIColor.white.cgColor
profilePicture.addTarget(self, action: #selector(handleSelectedPhoto), for: .touchUpInside)
view.addSubview(profilePicture)
profilePicture.translatesAutoresizingMaskIntoConstraints = false
profilePicture.heightAnchor.constraint(equalToConstant: 150).isActive = true
profilePicture.widthAnchor.constraint(equalToConstant: 150).isActive = true
profilePicture.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
profilePicture.topAnchor.constraint(equalTo: view.topAnchor, constant: 110).isActive = true
// SetUp UsernameTextfield:
usernameTextField.backgroundColor = .white
usernameTextField.attributedPlaceholder = NSAttributedString(string: "Username", attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightGray])
usernameTextField.textAlignment = NSTextAlignment.center
usernameTextField.layer.cornerRadius = 8
usernameTextField.layer.borderWidth = 1
usernameTextField.layer.borderColor = UIColor.lightGray.cgColor
self.view.addSubview(usernameTextField)
let username = usernameTextField.text
usernameTextField.translatesAutoresizingMaskIntoConstraints = false
usernameTextField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20).isActive = true
usernameTextField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20).isActive = true
usernameTextField.heightAnchor.constraint(equalToConstant: 50).isActive = true
usernameTextField.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
// SetUpEmailTextfield:
emailTextField.backgroundColor = .white
emailTextField.attributedPlaceholder = NSAttributedString(string: "Email", attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightGray])
emailTextField.textAlignment = NSTextAlignment.center
emailTextField.layer.cornerRadius = 8
emailTextField.layer.borderWidth = 1
emailTextField.layer.borderColor = UIColor.lightGray.cgColor
self.view.addSubview(emailTextField)
emailTextField.translatesAutoresizingMaskIntoConstraints = false
emailTextField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20).isActive = true
emailTextField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20).isActive = true
emailTextField.heightAnchor.constraint(equalToConstant: 50).isActive = true
emailTextField.topAnchor.constraint(equalTo: usernameTextField.bottomAnchor, constant: 20).isActive = true
```
Just I set for profilePicture and usernameTextField but for others are same it works. Wrong side of your code is about constraint and you add object two different views. There is a solution.
let stackView = UIStackView()
var profilePicture = UIButton()
var profileIcon = UIImage()
let usernameTextField = UITextField()
let emailTextField = UITextField()
let passswordTextField = UITextField()
let signInButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.prefersLargeTitles = true
navigationItem.title = "Create an Account"
view.backgroundColor = .white
// SetUp StackView:
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.alignment = .center
stackView.distribution = .fillEqually
stackView.spacing = 50
view.addSubview(stackView)
// SetUp Stack View Constraints:
stackView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20).isActive = true
stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20).isActive = true
stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20).isActive = true
//Add Elements
stackView.addArrangedSubview(profilePicture)
stackView.addArrangedSubview(usernameTextField)
// MARK: - Set-Up View-Elements
// SetUp ProfileIcon:
profileIcon = UIImage(named: "characteer")!
profilePicture.setImage(profileIcon, for: .normal)
profilePicture.imageView?.contentMode = .scaleAspectFill
let cornerRadius: CGFloat
cornerRadius = 75 // half of widht/height
profilePicture.layer.cornerRadius = cornerRadius
profilePicture.layer.masksToBounds = true
profilePicture.layer.borderWidth = 1
profilePicture.layer.borderColor = UIColor.white.cgColor
//profilePicture.addTarget(self, action: #selector(handleSelectedPhoto), for: .touchUpInside)
profilePicture.translatesAutoresizingMaskIntoConstraints = false
profilePicture.heightAnchor.constraint(equalToConstant: 150).isActive = true
profilePicture.widthAnchor.constraint(equalToConstant: 150).isActive = true
// SetUp UsernameTextfield:
usernameTextField.backgroundColor = .white
usernameTextField.attributedPlaceholder = NSAttributedString(string: "Username", attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightGray])
usernameTextField.textAlignment = NSTextAlignment.center
usernameTextField.layer.cornerRadius = 8
usernameTextField.layer.borderWidth = 1
usernameTextField.layer.borderColor = UIColor.lightGray.cgColor
let username = usernameTextField.text
usernameTextField.translatesAutoresizingMaskIntoConstraints = false
usernameTextField.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.width-40).isActive = true
usernameTextField.heightAnchor.constraint(equalToConstant: 50).isActive = true
You're doing a number of things wrong... It would be well worth your while to go through a few tutorials on auto-layout and using UIStackView.
First, if you add a view (image view, text field, label, button, etc) to a stack view, do not also give those views position constraints. That's what the stack view is doing.
Second, once you've added a view:
stackView.addArrangedSubview(profilePicture)
do not then add it as a subview like this:
view.addSubview(profilePicture)
Doing that will remove profilePicture from the stack view.
Take a look through your code -- review the comments where I've made changes:
class RegisterViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
let stackView = UIStackView()
var profilePicture = UIButton()
var profileIcon = UIImage()
let usernameTextField = UITextField()
let emailTextField = UITextField()
let passswordTextField = UITextField()
let signInButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.prefersLargeTitles = true
navigationItem.title = "Create an Account"
view.backgroundColor = .white
// SetUp StackView:
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.alignment = .center
// distribution should be .fill NOT .fillEqually
stackView.distribution = .fill
stackView.spacing = 50
view.addSubview(stackView)
// SetUp Stack View Constraints:
stackView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20).isActive = true
stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
//Add Elements
stackView.addArrangedSubview(profilePicture)
stackView.addArrangedSubview(usernameTextField)
stackView.addArrangedSubview(emailTextField)
stackView.addArrangedSubview(passswordTextField)
stackView.addArrangedSubview(signInButton)
// MARK: - Set-Up View-Elements
// SetUp ProfileIcon:
//profileIcon = UIImage(named: "characteer")!
profileIcon = UIImage(named: "pro1")!
profilePicture.setImage(profileIcon, for: .normal)
profilePicture.imageView?.contentMode = .scaleAspectFill
let cornerRadius: CGFloat
cornerRadius = 75 // half of widht/height
profilePicture.layer.cornerRadius = cornerRadius
profilePicture.layer.masksToBounds = true
profilePicture.layer.borderWidth = 1
profilePicture.layer.borderColor = UIColor.white.cgColor
//profilePicture.addTarget(self, action: #selector(handleSelectedPhoto), for: .touchUpInside)
// NO - it's already in the stack view
//view.addSubview(profilePicture)
// Set Only Width and Height - position is managed by the stack view
profilePicture.heightAnchor.constraint(equalToConstant: 150).isActive = true
profilePicture.widthAnchor.constraint(equalToConstant: 150).isActive = true
// SetUp UsernameTextfield:
usernameTextField.backgroundColor = .white
usernameTextField.attributedPlaceholder = NSAttributedString(string: "Username", attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightGray])
usernameTextField.textAlignment = NSTextAlignment.center
usernameTextField.layer.cornerRadius = 8
usernameTextField.layer.borderWidth = 1
usernameTextField.layer.borderColor = UIColor.lightGray.cgColor
// NO - it's already in the stack view
// self.view.addSubview(usernameTextField)
let username = usernameTextField.text
// Set Only Width and Height - position is managed by the stack view
usernameTextField.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -40).isActive = true
usernameTextField.heightAnchor.constraint(equalToConstant: 50).isActive = true
// SetUpEmailTextfield:
emailTextField.backgroundColor = .white
emailTextField.attributedPlaceholder = NSAttributedString(string: "Email", attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightGray])
emailTextField.textAlignment = NSTextAlignment.center
emailTextField.layer.cornerRadius = 8
emailTextField.layer.borderWidth = 1
emailTextField.layer.borderColor = UIColor.lightGray.cgColor
// NO - it's already in the stack view
// self.view.addSubview(emailTextField)
// Set Only Width and Height - position is managed by the stack view
emailTextField.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -40).isActive = true
emailTextField.heightAnchor.constraint(equalToConstant: 50).isActive = true
// SetUp PasswordTextfield:
passswordTextField.backgroundColor = .white
passswordTextField.attributedPlaceholder = NSAttributedString(string: "Password", attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightGray])
passswordTextField.textAlignment = NSTextAlignment.center
passswordTextField.layer.cornerRadius = 8
passswordTextField.layer.borderWidth = 1
passswordTextField.layer.borderColor = UIColor.lightGray.cgColor
// NO - it's already in the stack view
// self.view.addSubview(emailTextField)
// Set Only Width and Height - position is managed by the stack view
passswordTextField.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -40).isActive = true
passswordTextField.heightAnchor.constraint(equalToConstant: 50).isActive = true
signInButton.setTitle("Sign In", for: [])
signInButton.backgroundColor = .blue
// Set Only Width and Height - position is managed by the stack view
signInButton.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -40).isActive = true
signInButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
}
}
Of course, using that layout - where you specified vertical spacing between the elements of 50-pts, and you've set explicit heights for each element, you'll likely find that it doesn't "fit quite right" across different devices / screen sizes.
So, as pointed out to you in your previous question here: Why is my VC displaced after changing the Simulator? AutoLayout - you probably want to change the stack view's Distribution to Equal Spacing and add a bottom constraint:
stackView.distribution = .equalSpacing
stackView.spacing = 0
stackView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -20).isActive = true
That may or may not give you exactly what you want, but it's a starting point.
I think there is a problem about your constraint.
profilePicture.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
profilePicture.topAnchor.constraint(equalTo: view.topAnchor, constant: 110).isActive = true
are trying to center of the screen but they are inside of stack view. Also you have to give a static height to stack view on this scenario.

Center UIStackView not centering view

I have this
view.addSubview(myName)
myName.topAnchor.constraint(equalTo: myImage.bottomAnchor).isActive = true
myName.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
myName.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
let stackView = UIStackView(arrangedSubviews: [myValue1,myValue2])
view.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.alignment = .center
stackView.topAnchor.constraint(equalTo: myName.bottomAnchor).isActive = true
Any idea why it looks like this? I want it to be centered vertically like Example Text, I've tried adding
stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
but then it looks like this
Any idea what I'm missing?
Try
stackView.centerXAnchor.constraint(equalTo: myName.centerXAnchor).isActive = true
This should center the stack view itself against the myName label
note that if you want stuff in stack view to align nicely you have to give it some proportional or fixed widths, and give your stackview a width.
Update
if you want space between labels, add an extra UIView() between them into the stack:
let spacer = UIView()
spacer.widthAnchor.constraint(equalToConstant: 40.0).isActive = true
let stackView = UIStackView(arrangedSubviews: [myValue1,spacer, myValue2])

Why UITextView scroll not working on tvOS?

I have UITextView:
private let descriptionView: UITextView = {
let view = UITextView()
view.translatesAutoresizingMaskIntoConstraints = false
view.bounces = true
view.textColor = UIColor.white
view.font = UIFont(name: Fonts.regular, size: 28)
view.isSelectable = true
view.isUserInteractionEnabled = true
view.panGestureRecognizer.allowedPressTypes = [NSNumber(value: UITouch.TouchType.indirect.rawValue)]
view.showsVerticalScrollIndicator = true
return view
}()
Added in another view
addSubview(descriptionView)
addConstraints([
descriptionView.leadingAnchor.constraint(equalTo: title.leadingAnchor),
descriptionView.topAnchor.constraint(equalTo: ratings.bottomAnchor, constant: 60),
descriptionView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -80),
descriptionView.bottomAnchor.constraint(equalTo: bottomAnchor)
])
isSelectable = true,
view.isUserInteractionEnabled = true.
View focuses great, but not scrolling.
Content height > textview height
Similar questions did't help

Cannot change label position in stackview swift

I want to change X position of a label inside a stackview, there is a button inside the stackview as well. However, I am not able to change the label's position as once I set constraints for the label, errors jump out and want me to delete the constraints.
This is an example of a stackview with a button and a label with changes to the label's x position.
import UIKit
class ViewController: UIViewController {
let stackView = UIStackView()
override func viewDidLoad() {
super.viewDidLoad()
stackView.axis = .vertical
stackView.distribution = .equalSpacing
stackView.alignment = .center
view.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
stackView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
stackView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
let button = UIButton()
button.setTitle("Button", for: .normal)
button.setTitleColor(UIColor.black, for: .normal)
button.backgroundColor = UIColor.lightGray
stackView.addArrangedSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
button.leftAnchor.constraint(equalTo: stackView.leftAnchor).isActive = true
button.rightAnchor.constraint(equalTo: stackView.rightAnchor).isActive = true
let label = UILabel()
label.text = "Label"
label.textColor = UIColor.black
label.backgroundColor = UIColor.lightGray
stackView.addArrangedSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
// Modify left/right anchor constraints for label x position
label.leftAnchor.constraint(equalTo: stackView.leftAnchor, constant: 24).isActive = true
label.rightAnchor.constraint(equalTo: stackView.rightAnchor).isActive = true
}
}

Swift UIStackView: Positioning elements from center programmatically

I am trying to get elements inside a UIStackView to position themselves equally from the center.
This is the desired effect I would like:
As you can see, I would like the two text fields to be equally spaced from each other and aligned center within the stack view.
This stack view will have either 1 - 7 textfields that I need lined up.
Here is what is currently coming out:
This is how I am setting the Text Fields
let textLabel = UILabel()
textLabel.backgroundColor = UIColor.red
textLabel.widthAnchor.constraint(equalToConstant: 40.0).isActive = true
textLabel.heightAnchor.constraint(equalToConstant: 20.0).isActive = true
textLabel.text = "Hi"
textLabel.textAlignment = .center
let textLabel1 = UILabel()
textLabel1.backgroundColor = UIColor.red
textLabel1.widthAnchor.constraint(equalToConstant: 40.0).isActive = true
textLabel1.heightAnchor.constraint(equalToConstant: 20.0).isActive = true
textLabel1.text = "Hi"
textLabel1.textAlignment = .center
I am generating the stack view like so:
//Stack View
let stackView = UIStackView()
stackView.axis = UILayoutConstraintAxis.horizontal
stackView.distribution = UIStackViewDistribution.equalCentering
stackView.alignment = UIStackViewAlignment.fill
stackView.spacing = 16.0
stackView.addArrangedSubview(textLabel)
stackView.addArrangedSubview(textLabel1)
stackView.translatesAutoresizingMaskIntoConstraints = false;
self.view.addSubview(stackView)
//Constraints
stackView.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 50).isActive = true
stackView.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -50).isActive = true
stackView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 100).isActive = true
How do I get the elements inside to align center?
I thought it was
UIStackViewDistribution.equalCentering
However, that didn't do much.
Thats odd. Normally a horizontal UIStackView with center alignment and equal centering distribution should do exactly that:
But maybe I'm not understanding you correct and you actually want something like this:
In which case you have to chose Fill Equally as the distribution method and make the labels itself center their text: