从 UIStackView 中缺失的代码添加的 UITextView [英] UITextView added from code missing in UIStackView
问题描述
我正在尝试以编程方式将 UITextView
添加到 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.
这是我的代码:
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)
按钮添加得很好.但是我找不到正确显示 TextView 的方法!尝试添加如下所示的宽度/高度约束,但效果不佳或效果不佳(取决于变体):
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)
但是,当我添加 UITextField
而不是 UITextView
时,它可以正常工作,没有任何限制.
However, when I added a UITextField
, not UITextView
, then it's working fine without any constraints.
推荐答案
我发现缺少什么.我无法使用指定的初始化程序,因为我不知道我正在创建它的类中文本视图的框架大小.
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.
但这有帮助 - 在上面的代码中的 stackView.distribution 之后添加这一行:
But this helped - adding this line after stackView.distribution in the code above:
self.alignment = UIStackViewAlignment.Fill
这篇关于从 UIStackView 中缺失的代码添加的 UITextView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!