Skip to content

Instantly share code, notes, and snippets.

@lujop
Created November 24, 2016 11:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lujop/3a6af51c8c47e7d65195400bea5c79c8 to your computer and use it in GitHub Desktop.
Save lujop/3a6af51c8c47e7d65195400bea5c79c8 to your computer and use it in GitHub Desktop.
Problem applying constraint to UIStackView
// File.swift
// Medicaments
//
// Created by Joan Pujol Espinar on 22/11/2016.
// Copyright © 2016 Joan Pujol. All rights reserved.
//
import UIKit
class TestVC : UIViewController {
var scrollView: UIScrollView!
var stackView: UIStackView!
override func viewDidLoad() {
super.viewDidLoad()
scrollView = UIScrollView()
scrollView.backgroundColor = UIColor.cyan
scrollView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(scrollView)
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[scrollView]|", options: .alignAllCenterX, metrics: nil, views: ["scrollView": scrollView]))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[scrollView]|", options: .alignAllCenterX, metrics: nil, views: ["scrollView": scrollView]))
stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.spacing = 15
//stackView.backgroundColor = UIColor.gray
scrollView.addSubview(stackView)
scrollView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[stackView]|", options: NSLayoutFormatOptions.alignAllCenterX, metrics: nil, views: ["stackView": stackView]))
scrollView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[stackView]|", options: NSLayoutFormatOptions.alignAllCenterX, metrics: nil, views: ["stackView": stackView]))
for _ in 1 ... 20 {
let textLabel = UILabel()
textLabel.backgroundColor = UIColor.yellow
textLabel.text = "Hi World xxxx"
stackView.addArrangedSubview(textLabel)
textLabel.widthAnchor.constraint(equalTo: stackView.widthAnchor).isActive = true //Doesn't work as expected
//textLabel.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true //Work as expected
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment