Search code examples
iosswiftautolayoutuicollectionviewcell

AutoLayout: Child View goes Over Parent View's Bounds


I'm new to iOS development. I have a contentView for a UICollectionViewCell and I want to add another view to it. I want this new view to be stretched to the contentView edges. I'm trying to achieve this using AutoLayout, so here is what I did:

let view = UIView();
view.backgroundColor = UIColor.yellow
contentView.addSubview(view)

view.translatesAutoresizingMaskIntoConstraints = false
view.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
view.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
view.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
view.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true

This worked as expected and I got the behavior that I want. Then I wanted the contentView to have a padding of 18 points, so I figured that I need to add the constant parameter and set it to 18 like this:

view.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 18).isActive = true
view.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 18).isActive = true
view.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 18).isActive = true
view.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: 18).isActive = true

What I was expecting is that the new view now would have a smaller area than before, since it is now pushed from all directions by 18 points. What I did get though is a view with the same size as in the first scenario that is pushed by 18 points from the top and the left and goes over the bounds of the contentView!

Can you please tell me what's wrong with my code?


Solution

  • Your constants are all pointing in the same direction, so the view is just offset.

    This should work:

    view.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 18).isActive = true
    view.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -18).isActive = true
    view.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 18).isActive = true
    view.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -18).isActive = true