2

I'm trying to add view to a StackView with a button:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var stackOutlet: UIStackView!
    @IBOutlet weak var buttonOutlet: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func buttonAction(_ sender: AnyObject) {
        let newView = UIView(frame: CGRect(x: 0, y: 0, width: 240, height: 128))
        newView.heightAnchor.constraint(equalToConstant: 128)
        newView.widthAnchor.constraint(equalToConstant: 240)
        newView.backgroundColor = UIColor.green

        stackOutlet.addArrangedSubview(newView)
        stackOutlet.heightAnchor.constraint(equalToConstant: stackOutlet.frame.size.height + 128)
        print(stackOutlet.subviews.count)
    }
}

The number of subviews is increasing, but nothing is changing on the screen. I suspect that my StackView doesnt resize properly right ?

Anh Pham
  • 2,108
  • 9
  • 18
  • 29
petaire
  • 495
  • 1
  • 10
  • 23

1 Answers1

5

Nevermind I found a solution :

newView.widthAnchor.constraint(equalToConstant: 240).isActive = true
newView.heightAnchor.constraint(equalToConstant: 128).isActive = true

You need the .isActive = true

petaire
  • 495
  • 1
  • 10
  • 23