dorsz dorsz - 11 months ago 60
iOS Question

UITextView added from code missing in UIStackView

I'm trying to add a

programatically, but it doesn't appear on the screen.

When I check in Debug View Hierarchy, it is in the view hierarchy and it has some constraints but doesn't show up in the outputted view.

This is my code:

let stackView = UIStackView()

let textView = UITextView()
let button = UIButton()

stackView.axis = .Horizontal
stackView.spacing = 20
stackView.distribution = UIStackViewDistribution.Fill

button.setImage(UIImage(named:"image1"), forState: .Normal)
button.setImage(UIImage(named:"image2"), forState: .Selected)

textView.textAlignment = NSTextAlignment.Left
textView.textColor = UIColor.blackColor()
textView.editable = true
textView.text = ""


Button is added fine. But I cannot find a way to show TextView correctly! Tried to add width/height constraints like below, but it doesn't work like, or work badly (depending on variant):

let widthConstraint = NSLayoutConstraint(item: textView,
attribute: NSLayoutAttribute.Width,
relatedBy: NSLayoutRelation.Equal,
toItem: stackView,
attribute: NSLayoutAttribute.Width,
multiplier: 1,
constant: 0)
let heightConstraint = NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: stackView, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 0)

However, when I added a
, not
, then it's working fine without any constraints.

Answer Source

I figured out what's missing. I can't use the designated initializer, because I don't know the frame size of the text view in the class I'm creating it in.

But this helped - adding this line after stackView.distribution in the code above:

 self.alignment = UIStackViewAlignment.Fill