How to programmatically change restrictions on two buttons?

In one view, there are two buttons with the name buttonAand buttonB, I set their limitations in the storyboard. How can I exchange my restrictions programmatically?

+4
source share
2 answers

I searched for the answer, and I ended it up as follows: (Code examples are given in Swift 3)

Say you have a UIView called containerView, which contains two UIViews: subviewAand subviewB.

The restrictions for subviews are actually defined internally containerView(according to the "closest common ancestor" rule).

, " " subviewA subviewB " " containerView. , .

, , :

private func swapFirstItemsOfConstraintsDefinedInThisView(_ superview: UIView, betweenItem item1: AnyObject, andItem item2: AnyObject)
{
    var constraintsToRemove: [NSLayoutConstraint]  = []
    var constraintsNew_item1: [NSLayoutConstraint]  = []
    var constraintsNew_item2: [NSLayoutConstraint]  = []

    for constraint in superview.constraints
    {
        if (constraint.firstItem === item1)
        {
            constraintsToRemove.append(constraint)
            constraintsNew_item1.append(NSLayoutConstraint(item: item2, attribute: constraint.firstAttribute, relatedBy: constraint.relation, toItem: constraint.secondItem, attribute: constraint.secondAttribute, multiplier: constraint.multiplier, constant: constraint.constant))
        }
        else if (constraint.firstItem === item2)
        {
            constraintsToRemove.append(constraint)
            constraintsNew_item2.append(NSLayoutConstraint(item: item1, attribute: constraint.firstAttribute, relatedBy: constraint.relation, toItem: constraint.secondItem, attribute: constraint.secondAttribute, multiplier: constraint.multiplier, constant: constraint.constant))
        }
    }

    superview.removeConstraints(constraintsToRemove);
    superview.addConstraints(constraintsNew_item1);
    superview.addConstraints(constraintsNew_item2);
}

, ( ViewController -):

self.swapFirstItemsOfConstraintsDefinedInThisView(self.containerView, betweenItem: subviewA, andItem: subviewB)
self.containerView.layoutIfNeeded()

, , layoutIfNeeded(). .

, layoutIfNeeded() UIAnimation ( / animations), .

, , . , NSLayoutConstraint, init , NSLayoutConstraint " " ( ). UIView. .

+2

Source: https://habr.com/ru/post/1599254/


All Articles