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.
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)
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
Try using
init(frame frame: CGRect,textContainer textContainer: NSTextContainer?)
As it's the designated initializer for a UITextView.
来源:https://stackoverflow.com/questions/33497528/uitextview-added-from-code-missing-in-uistackview