-1

Programmatically I'm trying to create a stack view with 5 buttons using auto layout. When i run the project then it run's without showing any error but it is not showing the button stack.

On the other-hand in Debug View Hierarchy, it is showing "View has ambigous layout." What I'm missing here.

class TestView: UIView {
var stackView = UIStackView()
override init(frame: CGRect) {
    super.init(frame: frame)
    initComponents()
}
func initComponents() {
    self.autoresizesSubviews = false
    stackView.autoresizesSubviews = false
    stackView.translatesAutoresizingMaskIntoConstraints = false
    stackView.distribution = .equalSpacing
    stackView.axis = .horizontal
    stackView.alignment = .fill
    stackView.contentMode = .scaleToFill
    addSubview(stackView)
    NSLayoutConstraint.activate([
        stackView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
        stackView.trailingAnchor.constraint(equalTo: self.trailingAnchor),
        stackView.topAnchor.constraint(equalTo: self.topAnchor),
        stackView.bottomAnchor.constraint(equalTo: self.bottomAnchor),
        ])
    for i in 0...4 {
        let button = UIButton()

        button.titleLabel?.text = "\(i)"
        button.translatesAutoresizingMaskIntoConstraints = false

        stackView.addSubview(button)

        button.heightAnchor.constraint(equalTo: stackView.heightAnchor, multiplier: 1).isActive = true
        button.widthAnchor.constraint(equalTo: button.heightAnchor, multiplier: 1).isActive = true
    }
}
required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}}

In ViewController.swift file

let frame = CGRect(x: 0, y: 0, width: 200, height: 30)
    let test = TestView.init(frame: frame)
    self.view.addSubview(test)
Tanvir Nayem
  • 702
  • 10
  • 25
WAHID MARUF
  • 51
  • 1
  • 8

1 Answers1

0

I had to change a few things to make this work:

  1. Use button.setTitle(_:for:) to set the title of the buttons.
  2. Set a color for your text with button.setTitleColor(_:for:).
  3. Set a background color for your buttons.
  4. Add the buttons to the stackView with stackView.addArrangedSubview(button).

Also, you might want to move the frame down a bit. It's in the upper left corner which puts it over top of the status bar and behind the notch of the iPhone X.


for i in 0...4 {
    let button = UIButton()

    button.setTitle("\(i)", for: .normal)
    button.translatesAutoresizingMaskIntoConstraints = false

    // Set these colors to whatever you like
    button.setTitleColor(.black, for: .normal)
    button.backgroundColor = .red

    stackView.addArrangedSubview(button)

    button.heightAnchor.constraint(equalTo: stackView.heightAnchor, multiplier: 1).isActive = true
    button.widthAnchor.constraint(equalTo: button.heightAnchor, multiplier: 1).isActive = true
}
vacawama
  • 150,663
  • 30
  • 266
  • 294