简体   繁体   中英

Horizontal auto-layout constraint

In a subclass of UITableViewCell, I am trying to use auto layout.

Here is what I want to do : 布局

Here is my code which doesn't work : only one view is shown

import Foundation

class CustomCell: UITableViewCell {

    func configureCell() {

        backgroundColor = UIColor.yellowColor()

        let redColorView = UIView()
        redColorView.backgroundColor = UIColor.redColor()
        redColorView.translatesAutoresizingMaskIntoConstraints = false

        let blueColorView = UIView()
        blueColorView.backgroundColor = UIColor.blueColor()
        blueColorView.translatesAutoresizingMaskIntoConstraints = false

        addSubview(blueColorView)
        addSubview(redColorView)

        let viewsDictionary = ["blue":blueColorView,"red":redColorView]

        let layout = NSLayoutFormatOptions(rawValue: 0)

        let horizontalContraint:[NSLayoutConstraint] = NSLayoutConstraint.constraintsWithVisualFormat("|-10-[blue]-10-[red]-10-|", options: layout, metrics: nil, views: viewsDictionary)

        let verticalContraint_1:[NSLayoutConstraint] = NSLayoutConstraint.constraintsWithVisualFormat("V:|-10-[blue]-10-|", options: layout, metrics: nil, views: viewsDictionary)

        let verticalContraint_2:[NSLayoutConstraint] = NSLayoutConstraint.constraintsWithVisualFormat("V:|-10-[red]-10-|", options: layout, metrics: nil, views: viewsDictionary)

        self.addConstraints(verticalContraint_1)
        self.addConstraints(verticalContraint_2)
        self.addConstraints(horizontalContraint)
    }
}

The problem is that your horizontal constraints are ambiguous. They are insufficient to resolve to exactly one layout. So, the system has to pick arbitrarily from among the possibilities.

In particular, |-10-[blue]-10-[red]-10-| doesn't specify how wide blue and red should be. Assuming the superview is wider than 30 points, any number of solutions are possible. blue could be 0 width and red could be the superview's width minus 30. Or vice versa. Or anything in between. The only effective constraint on the two subviews' widths is that they add up to the superview's width minus 30. Since you say that only one is visible, presumably the other has been assigned 0 width.

As you've noticed, you can explicitly constrain the width one of the subview or you can specify that they have equal width to each other (or some other ratio).

If the views had intrinsic size, or if they had subviews with intrinsic size and their widths were constrained based on their subviews, then things like content-hugging and compression-resistance priorities would come into play. But plain UIView s like you're using have no intrinsic size, so they don't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM