A O
A O

Reputation: 5698

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

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

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". As you can see my trailing and bottom constraints are ignored (no exceptions in console either)

enter image description here

For comparison, here are the runtime constraints when I added the UILabel into a UIView instead of a UITextView

enter image description here

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?

Upvotes: 0

Views: 292

Answers (1)

MartinM
MartinM

Reputation: 937

The reason behind this behavior is that a UITextView is a 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.

Upvotes: 2

Related Questions