BlackDeveraux BlackDeveraux - 3 months ago 20
Swift Question

Trouble with UIView Constraints

To start with, here's a mockup of the layout I'm trying to accomplish in Swift.
Mockup

And here's what I have so far,
Error

So here's the problem. Notice that in the second image the green UIView overflows exceeding the TableViewCell height.

In my Main TableViewController class I've defined each cell to be 120 pixels in height, and the green UIView 10 pixels short of the cell height with the 10 pixels on top as a separator between subsequent cells.

Cell height definition:

var itemHeight = [CGFloat](count: 2, repeatedValue: 120.0)


UIView constraints:

foregroundView.topAnchor.constraintEqualToAnchor(foregroundView.superview?.topAnchor, constant: 10).active = true
foregroundView.leftAnchor.constraintEqualToAnchor(foregroundView.superview?.leftAnchor, constant: 20).active = true
foregroundView.widthAnchor.constraintEqualToAnchor(foregroundView.superview?.widthAnchor, constant: -40).active = true
foregroundView.heightAnchor.constraintEqualToConstant(110).active = true


Any ideas on what might be causing the UIView overflow?
Thanks in advance!

Please let me know if you'd like to see the code in context :)

Answer

Remove two lines of code from your project:

foregroundView.layoutIfNeeded()

And

containerView.layoutIfNeeded()

They are forcing an untimely laying out of content that is causing your problem.

Comments