繁体   English   中英

将 UIStackView 与具有动态高度的 UITextView 一起使用

[英]Using UIStackView with a UITextView with dynamic height

我刚刚发现有关 UIStackView 的信息,我正在尝试查看它是否最终可以更轻松地布置扩展内容。

具体来说,我想做以下事情:

|-- UITextView ------------|
| some dynamic text here,  |  I want the text view's height to change
| it could be short, or it |  depending on the height of the text
| could be tall            |  (set later, in code)
|-- UIView ----------------|
|xxxxxxxxxxxxxxxxxxxxxxxxxx|  I want this view to expand to fill the 
|xxxxxxxxxxxxxxxxxxxxxxxxxx|  vertical space.
|xxxxxxxxxxxxxxxxxxxxxxxxxx|  
|xxxxxxxxxxxxxxxxxxxxxxxxxx|  It should start right below the
|xxxxxxxxxxxxxxxxxxxxxxxxxx|  bottom of the UITextView
|xxxxxxxxxxxxxxxxxxxxxxxxxx|
|--------------------------|

我想我知道如何在常规约束下做到这一点。 可以用 UIStackView 吗? 我可能理解 UIStackView 的用途,但我希望能够更轻松地创建这样的布局。

当我将这两个都放入 UIStackView 时,界面生成器会为两个视图显示“需要约束:Y position 或高度”。

您可以添加一个 stackview,然后在其中添加一个 textview,然后设置 scrollable false,它会自动处理您的问题

在textview中计算文本高度,在uitextview上添加高度限制,例如20,然后计算高度即可,只需更改高度限制。从textview给出以下top 0的视图限制,您的问题将得到解决。 使用此功能计算高度

let height = string.boundingRectWithSize(CGSizeMake(CGFloat.max,textviewwidth), options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font!], context: nil).size.height

以编程方式,它看起来像这样:

@IBOutlet private var stackView: UIStackView! 
{
    didSet {
        stackView.addArrangedSubview(titleTextView)
        stackView.addArrangedSubview(UIView())
    }
}

lazy var titleTextView: UITextView = 
{
    let textView = UITextView()
    textView.isScrollEnabled = false
    return textView
}()

您不需要其他任何内容即可自动扩展UITextView。 这不应该抱怨模棱两可。

尝试使用行= 0的UILabel代替UITextView。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM