When do I need to use Priority in iOS AutoLayout?

Using iOS AutoLayout, you will do something like:

self.view.addConstraint(NSLayoutConstraint(item: label, 
   attribute: .Width, 
   relatedBy: .Equal, 
   toItem: self.view, 
   attribute: .Width, 
   multiplier: 0.3, 
   constant: 0))

You can also use priority for each layout constraint.

When do I need to use Priority in iOS AutoLayout?

+4
source share
2 answers

You can use it to approximate conditional logic.

For example, I had a crop view (imagine a circular cutout for a face profile). If the image was a portrait, I wanted the circle to be closer to the top, but if the image was landscape, there would be no place for it to be off-center, and that would not make sense.

, - ( < =/" >= ). , , , , , , , . , . , AL .

- , , , , , . , , , , , , , . AL , - , , . .

. :

    self.addConstraints([

        // absolute constraints
        self.leftMarginConstraint,
        self.rightMarginConstraint,
        self.topMarginConstraint,
        self.bottomMarginConstraint,
        self.aspectRatioConstraint,
        self.constrain(self.maskContainer, self, .CenterX, .Equal),

        // hug the edges as much as possible, but only two of the four will be used
        self.constrain(self.maskContainer, self, .Left, .Equal, priority:900),
        self.constrain(self, self.maskContainer, .Right, .Equal, priority:900),
        self.constrain(self.maskContainer, self, .Top, .Equal, priority:900),
        self.constrain(self, self.maskContainer, .Bottom, .Equal, priority:900),

        // try for above center, but accept vertically centered
        self.constrain(self.maskContainer, self, .CenterY, .Equal, priority:800, multiplier:0.8),
        self.constrain(self.maskContainer, self, .CenterY, .Equal, priority:500),
        ])
+1

, , . , , .

0

All Articles