dynamic placement of UIView's based on certain condition

Viewed 33

This is may be basic question, but need help on this - I have 4 UIViews as shown below in image. Based on certain conditions, I need to move hide UIView 2 and move all below UIView's. Similarly, hide UIview 3 and move other view.

How to do this using NSLayoutContraint in swift code ?

enter image description here

1 Answers

After throwing all views into a stackview, give the stackview's top, left, right constraints , give it a constant using its height less than equal and last give a fixed height with 750 Priority (Stackview's Distribituan must be Fill Equality).

Your stackview must be like

enter image description here

And constraints :

enter image description here

And in your view controller you must you need to recalculate the minimum height according to the number of items.

  @IBOutlet weak var minHeight: NSLayoutConstraint!
  @IBOutlet weak var perItemWidth: NSLayoutConstraint!
  var itemCount = 3
  var eachElementSpace = 10

  override func viewDidLoad() {
      super.viewDidLoad()
      view2.isHidden = true
      minHeight.constant = (perItemWidth.constant * CGFloat(itemCount)) + CGFloat(eachElementSpace) //
}

perItemWidth is height for height of any view in stackview

minHeight is a constant that you declared with 750 Priority

eachElementSpace is spacing between elements in stackview

Related