Search code examples
iosswiftautolayout

clipsToBounds seeming to have no effect in UIStackView


Is it possible to have a subview render outside a UIStackView? I have a vertical stack view with a button and a label, and I'm using the width of the stack view to set the button's height and width appropriately:

addArrangedSubview(self.loginMethodButton)
let widthConstraint = NSLayoutConstraint(item: self.loginMethodButton, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1.0, constant: 0.0)
let heightConstraint = NSLayoutConstraint(item: self.loginMethodButton, attribute: .height, relatedBy: .equal, toItem: self.loginMethodButton, attribute: .width, multiplier: 1.0, constant: 0.0)
NSLayoutConstraint.activate([widthConstraint, heightConstraint])

I then adjust the width in my viewController to appropriate sizes based on the situation. The problem is, in one of the smaller sizes the button needs to be, the width is smaller than the label beneath it, which cuts off the label.

enter image description here

If I call sizeToFit() when setting the label, it works, however, calling sizeToFit() when adjusting the sizes after the label has been set still results in the label being cut off. Setting clipsToBounds to false on both the label and stack view have no effect.

Is it possible to render a view outside of a stack view at all? Or am I going to have to find a way to re-work my constraints in order to fix this issue?


Solution

  • UIStackView is a "non-rendering" object... all it does is arrange other views.

    If the problem is that your UILabel is too wide to fit in the area made available by your Stack View, then you either need to set the label to "auto-shrink" the font, or you need to alter your Stack View constraints to allow for the wider label.

    Edit Based on your other comment, the following was incorrect.

    You need to set .clipsToBounds on the "containing" view... based on the graphic you are showing, that would be the darker-blue box (I'm assuming that is a UIView with the image and label as subviews).