Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically Change multiplier of Alignment Constraint of Center X / Y

How can I programmatically change the multiplier in the simplest way?

enter image description here

For Swift 2.0

like image 635
Jams Avatar asked Jan 20 '16 22:01

Jams


People also ask

How do I change the constraint multiplier in Swift?

Since multiplier is a read-only property and you can't change it, you need to replace the constraint with its modified clone.

How do you change the multiplier on NSLayoutConstraint?

You have to remove the old NSLayoutConstraint and replace it with a new one to modify it. However, since you know you want to change the multiplier, you can just change the constant by multiplying it yourself when changes are needed which is often less code.

What is NSLayoutConstraint in Swift?

The relationship between two user interface objects that must be satisfied by the constraint-based layout system.


2 Answers

So for Y, if you set the top of the image equal with a constant of 0 to the top of the superView. then enter this code:

@IBOutlet weak var topc: NSLayoutConstraint!


let heightOfSuperview = self.view.bounds.height
topc.constant = heightOfSuperview * 0.90 // this has the same effect as multiplier  

This is equivalent of Center.y multiplier = 0.9:1

like image 76
Jams Avatar answered Oct 21 '22 05:10

Jams


I try to use extension but it not work, but change to the global utility function and it work for me:

public class func changeMultiplier(constraint: NSLayoutConstraint, multiplier: CGFloat) -> NSLayoutConstraint {
    let newConstraint = NSLayoutConstraint(
        item: constraint.firstItem,
        attribute: constraint.firstAttribute,
        relatedBy: constraint.relation,
        toItem: constraint.secondItem,
        attribute: constraint.secondAttribute,
        multiplier: multiplier,
        constant: constraint.constant)

    newConstraint.priority = constraint.priority
    NSLayoutConstraint.deactivateConstraints([constraint])
    NSLayoutConstraint.activateConstraints([newConstraint])
    return newConstraint
}
like image 29
Huy Vu Avatar answered Oct 21 '22 05:10

Huy Vu