iosxcodeuiscrollviewswift3autoresizingmask

How to make views inside scrollers automatically resize by adding components to them? - Swift 3


I have a scroller, inside it I have a UIView element called ContentView. Inside ContentView i have a StackView that's filled with dynamically created buttons. I am adding buttons programmatically to the StackView, also I assign each button to the StackView:

self.stackView.addSubview(btn)

Buttons appear on runtime, however they are not clickable which I diagnosed to be because they are added outside ContentView and StackView bounds. I tried using:

self.stackViewButtons.autoresizingMask = UIViewAutoresizing.flexibleWidth
self.contentView.autoresizingMask = UIViewAutoresizing.flexibleWidth

however the contentView and stackView always stay the same size.

EDIT:

Constraints in storyboard:

UIScrollView has one element: ContentView which has 4 constraints - top, bottom, leading and trailing set towards superView - UIScrollView. (all 4 set to 0). Also vertical constraint that centers horizontally from ContentView to superView - UIScrollView. StackView is supposed to hold all the buttons - it has 4 constraints (top - 13, bottom - 13, leading - 10, trailing - 10) set towards superView which is ContentView.

My scrolls in other views work well with these constraints, however there I exactly know the number of buttons that I will have so I create them in the storyboard and change their constraint in the code, while now i have to create them from the code.


Solution

  • Ok, if someone passes by, this helped me a lot - scroll down to dynamic stack views. I am using Auto Layout and I am dynamically adding buttons to the stackView, my mistake was that I was using

    self.stackView.addSubview(btn)
    

    instead of:

    self.stackView.addArrangedSubview(btn)
    

    Using addSubview caused the content on scroller to always remain the same like pre-runtime.