从UIStackView中缺少的代码添加UITextView

dor*_*rsz 5 uitextview ios programmatically-created swift uistackview

我想要一个添加UITextViewUIStackView编程,但它不会出现在屏幕上.

当我检入调试视图层次结构时,它位于视图层次结构中,它有一些约束但不会显示在输出视图中.

这是我的代码:

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)
Run Code Online (Sandbox Code Playgroud)

按钮添加正常.但我找不到正确显示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)
Run Code Online (Sandbox Code Playgroud)

然而,当我添加一个UITextField,而不是UITextView,它没有任何约束,它的工作正常.

Avi*_*oss 12

UITextView是一个子类,UIScrollView因此它的大小在内部是模糊的UIStackVIew.为了使大小明确无误,你可以根据它的内容调整大小 - 即使其不可滚动.那么简单的解决方案就是:

textView.isScrollEnabled = false
Run Code Online (Sandbox Code Playgroud)

(Swift 3.0语法)


dor*_*rsz 2

我发现缺少了什么。我无法使用指定的初始值设定项,因为我不知道我在其中创建文本视图的类中的框架大小。

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

 self.alignment = UIStackViewAlignment.Fill
Run Code Online (Sandbox Code Playgroud)