Search code examples
swiftautolayoutnslayoutconstraintswift3

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?


Solution

  • 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.