从UIStackView中缺less的代码添加UITextView

我试图以编程方式将UITextView添加到UIStackView ,但它不出现在屏幕上。

当我检查Debug View Hierarchy时,它是在视图层次结构中,它有一些约束,但不显示在输出视图。

这是我的代码:

 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添加正常。 但我找不到正确显示TextView的方法! 试图添加像下面的宽度/高度约束,但它不工作,或工作不好(取决于变体):

 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) 

但是,当我添加一个UITextField ,而不是UITextView ,那么它工作正常,没有任何限制。

UITextViewUIScrollView的子类,因此在UIStackVIew它的大小是模糊的。 为了使大小明确,你可以根据它的内容来调整它自己的大小 – 例如使其不能滚动。 那么简单的解决scheme是:

 textView.isScrollEnabled = false 

(Swift 3.0语法)

我找出了缺less的东西。 我不能使用指定的初始值设定项,因为我不知道我正在创build它的类中的文本视图的框架大小。

但是这有助于 – 在上面的代码中的stackView.distribution之后添加这一行:

  self.alignment = UIStackViewAlignment.Fill 

尝试使用

 init(frame frame: CGRect,textContainer textContainer: NSTextContainer?) 

因为它是UITextView的指定初始值设定项。