Manuel Manuel - 1 year ago 81
Swift Question

How to define maximum width constraint with Auto-Layout?


is added to a
using Auto-Layout.

The width of the
should be 50% of the width of the
but in any case not larger than 50px.

This does not work:

cellImageView.topAnchor.constraint(equalTo: contentView.topAnchor),
cellImageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
cellImageView.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),
cellImageView.heightAnchor.constraint(equalTo: cellImageView.widthAnchor, multiplier: cellImage.size.height / cellImage.size.width),
cellImageView.widthAnchor.constraint(equalTo: contentView.widthAnchor, multiplier: 0.5),
cellImageView.widthAnchor.constraint(lessThanOrEqualToConstant: 50)

How do I have to define the layout constraints?

Answer Source

Is this a layout library? I'm not familiar with the syntax in your code, but based on your description, it sounds like the width constraints you want are:

  • lessThanOrEqualToConstant: 50
  • equalTo: contentView.widthAnchor, multiplier: 0.5 with a lower priority than the 50pt constraint.