Manuel
Manuel

Reputation: 15042

How to define maximum width constraint with Auto-Layout?

A UIImageView is added to a UITableViewCell using Auto-Layout.

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

This does not work:

    NSLayoutConstraint.activate([
        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?

Upvotes: 2

Views: 5269

Answers (2)

Connor Neville
Connor Neville

Reputation: 7361

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.

Upvotes: 3

Firo
Firo

Reputation: 15566

You would set up two separate constraints with different priorities. One constraint would be 50% width with a UILayoutPriority.DefaultHigh priority (e.g. 750) while the second constraint would be a 50 point constraint with UILayoutPriority.Required priority (e.g. 1000). This would then attempt to fulfill both constraints, but would break the 50% one if they ran into conflict (i.e. went over 50 points).

Upvotes: 1

Related Questions