15
votes

I know that there's a question similar to this already, but his solution didn't solve my problem.

What I have is, I've used the storyboard to create a view controller, and then place a child stack view ontop.

Using IBOutlet, I've linked the UIStackView to the custom view controller class.

Everything's linked together correctly, this isn't the issue (I've made sure).

My problem is I can't seem to get a UITextView to display in the UIStackView.

here's my code (inside a function in the view controller):

let textView = UITextView()
textView.text = "test"
stackView.addArrangedSubview(textView) //stackView is the IBOutlet

I've been able to make the UITextView appear on the parent view using

let pos = CGRect(x: 100, y: 100, width: 200, height: 200)
let textView = UITextField(frame: pos)
textView.text = "test"
//stackView.addArrangedSubview(textView)
self.view.addSubview(textView)

And no, it doesn't work to uncomment the line with stackView, then comment out the self.view.addSubview

But I manage to get something to appear in the UITabView if I use a UITextField. This is beyond annoying....

Any suggestions?

5

5 Answers

83
votes

The stack view does not know the size of the text view because it is scrollable by default. You need to disable scrolling:

textView.isScrollEnabled = false
3
votes

You have to add contraints of 0 left and right from text view to the stack view.

1
votes

You should not be mixing manual frame setting with AutoLayout (what UIStackView uses internally). @Lawrence413's answer is wrong and is using UIStackView incorrectly.

Below is a blog post describing UIStackView and how to use it: http://www.raizlabs.com/dev/2016/04/uistackview/

Take note of the UIStackViewDistribution and how it is used to resize arrangedSubviews.

1
votes

Disabling scrolling did not work for me, but setting a defined height using a height constraint worked for me. I did not use subviews - a height constraint directly on the UITextView is all that was needed in my case.

0
votes

You need a frame for the UITextView. And use addSubview instead of addArrangedSubview.

I used the following and a text view appeared just fine in the stack view:

let textView = UITextView(frame: CGRectMake(0, 0, 100, 100))
textView.text = "test"
textView.backgroundColor = UIColor.redColor()
stackView.addSubview(textView)