简体   繁体   English

将UILabel作为子视图添加到具有编程约束的UITextView时,如何停止“内容大小”约束

[英]How can I stop the “content size” constraints when adding a UILabel as a subview to a UITextView, with programmatic constraints

I have this UIVIew extension method 我有这个UIVIew扩展方法

func addSubviewWithConstrainedBounds(subview:UIView) {
    subview.translatesAutoresizingMaskIntoConstraints = false
    self.addSubview(subview)
    NSLayoutConstraint.activate([
        subview.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 0),
        subview.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: 0),
        subview.topAnchor.constraint(equalTo: self.topAnchor, constant: 0),
        subview.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0),
    ])
}

The idea being that I can programmatically add a view into another, where I'll leverage autolayout to match the bounds of the subview to the superview 我的想法是我可以以编程方式将视图添加到另一个视图中,在这里我将利用自动布局将子视图的边界与超级视图匹配

When I call this to add my subview to a UIView superview, it works 当我调用此方法将subview添加到UIView超级视图时,它可以工作

However, when I try to add my subview to a UITextView superview, the subview insists on taking some width and height constraints from "content size". 但是,当我尝试将subview添加到UITextView父视图时​​,该subview坚持要从“内容大小”中获取一些widthheight约束。 As you can see my trailing and bottom constraints are ignored (no exceptions in console either) 如您所见,我的尾部约束和底部约束都被忽略了(控制台中也没有例外)

在此处输入图片说明

For comparison, here are the runtime constraints when I added the UILabel into a UIView instead of a UITextView 为了进行比较,这是将UILabel添加到UIView而不是UITextView时的运行时约束。

在此处输入图片说明

am I potentially missing a property here? 我可能会在这里丢失财产吗? something that I need to set? 我需要设置的东西? or is this just a quirk of trying to add a subview to a UITextView ? 还是只是尝试将子视图添加到UITextView的怪癖?

The reason behind this behavior is that a UITextView is a UIScrollView. 此行为背后的原因是,UITextView是UIScrollView。 That means that if your subview does not have a height/width, your layout is ambiguous, so the layout engine adds the intrinsic size to resolve that issue. 这意味着,如果子视图没有高度/宽度,则布局是不明确的,因此布局引擎会添加固有尺寸来解决该问题。

It depends on how or where you want to position your subview in your textview, in that case you need to be more specific about the alignment. 这取决于您要在文本视图中放置子视图的方式或位置,在这种情况下,您需要更加明确地对齐。 Check out the options for content hugging priority if that helps you. 如果有帮助,请查看内容优先选项。

But in the end i think you might be better off to not add a label as a subview, if you can use TextKit's features to style and position the content of your planned label inside your textview. 但是最后,我认为如果可以使用TextKit的功能在textview中计划和放置计划标签的内容,最好不要添加标签作为子视图。

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

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