Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextView added from code missing in UIStackView

I'm trying to add a UITextView to UIStackView 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 = ""

stackView.addArrangedSubview(textView)
stackView.addArrangedSubview(button)

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)
stackView.addConstraint(widthConstraint)
let heightConstraint = NSLayoutConstraint(item: textView, attribute:   NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: stackView, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 0)
stackView.addConstraint(heightConstraint)

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

like image 586
dorsz Avatar asked Nov 03 '15 11:11

dorsz


1 Answers

UITextView is a subclass of UIScrollView and as such it's size is ambiguous inside UIStackVIew. To make the size unambiguous you make it resize itself based on it's content - i.e. make in not scrollable. The simple solution is then:

textView.isScrollEnabled = false

(Swift 3.0 syntax)

like image 90
Aviel Gross Avatar answered Oct 19 '22 19:10

Aviel Gross