SuperSans SuperSans - 1 year ago 83
iOS Question

Plain UIView not being added to UIStackView

I'm currently working on an iOS app in Swift that creating a list of objects. I'm using a UIStackView to organize these objects, and I'm starting off by making a UIView container which will hold mostly UILabels. I've run into an issue that has me confused, and I'm hoping someone with iOS experience can explain why it's happening. Here's my simple code so far:

override func viewDidLoad() {

for i in 0...5{
//Make card in here
let DynamicView=UITextView(frame: CGRectMake(0, 0, 100, 100))

let lbl = UILabel()
lbl.text="Label " + String(i)
lbl.backgroundColor = UIColor.whiteColor()
lbl.layer.borderColor = UIColor.lightGrayColor().CGColor
lbl.layer.borderWidth = 2.0


In this, I'm adding 6 labels to the StackView, which works successfully:
UILabels in UIStackView

You can see in the commented code that I try to add the UIView, which, before adding it to the UIStackView, looks like this:

UIView no add

When I add it to the UIStackView (and comment out the labels from earlier), the area where I would expect the UIViews to appear is blank:

After add

Am I doing something wrong in the code? Can UIViews not be added to UIStackViews?

Answer Source

I think you have not set the top, leading, bottom and trailing constraints for the Stack View. Also set the Distribution of the Stack View to Fill Equally.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download