UITextView added from code missing in UIStackView

↘锁芯ラ 提交于 2019-12-07 06:05:38

问题


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.


回答1:


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)




回答2:


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



回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!