Nischal Hada
Nischal Hada

Reputation: 3288

Change AutoLayout Constraints during Run Time

How is it possible to change AutoLayout Constraints during run time.

I need to change the coordinate of view during run time so i did following:

 if ([OfferText length] != 0) {
            cell.topContentView.translatesAutoresizingMaskIntoConstraints = YES;
            CGRect newFrame = CGRectMake( 71, 4, [Util window_width]-71,50);
            cell.topContentView.frame = newFrame;
        }

While doing that I get following warning. Is it possible to change the auto layout constraints during run time.

(1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
(
    "<NSLayoutConstraint:0x7fca729606a0 UIView:0x7fca7296c6e0.top == UITableViewCellContentView:0x7fca729712b0.topMargin + 2>",
    "<NSAutoresizingMaskLayoutConstraint:0x7fca7286f620 h=--& v=--& UIView:0x7fca7296c6e0.midY == + 29>",
    "<NSAutoresizingMaskLayoutConstraint:0x7fca7286f670 h=--& v=--& V:[UIView:0x7fca7296c6e0(50)]>",
    "<NSAutoresizingMaskLayoutConstraint:0x7fca705c9770 h=--& v=--& 'UIView-Encapsulated-Layout-Top' V:|-(0)-[UITableViewCellContentView:0x7fca729712b0]   (Names: '|':CollectionBrandCell:0x7fca72968820 )>"
)

I find my solution using following code:

in .h of tableviewcell In my case

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *constraintsTopContentView;

and in .m

if ([OfferText length] != 0) {
            cell.constraintsTopContentView.constant=-4;
        }

Upvotes: 1

Views: 1739

Answers (2)

Nirmit Dagly
Nirmit Dagly

Reputation: 1502

If you are setting up constraints from Storyboard, then make the outlet's of the constraints that are required to change the view's co-ordinates. For Example: If you want to change the top space of some view XYZ, then please do the following:

  1. Select that view's top constraint and make outlet in .h file. This will look like this.

    @property (strong, nonatomic) NSLayoutConstraint *XYZ'stopConstraint;

  2. Now, change this constraints constant, when you required by the following code.

    self.XYZ'stopConstraints.constant = youValue;

Also, please remove this line from your code as it is not necessary as per my view.

 cell.topContentView.translatesAutoresizingMaskIntoConstraints = YES;

Upvotes: 3

Gallgall
Gallgall

Reputation: 15

Create outlets for constraints you want to change (similar to UI controls); then change constant property of them. Your warning caused because you use cell.topContentView.translatesAutoresizingMaskIntoConstraints = YES;. This will creates some new constraints (NSAutoresizingMaskLayoutConstraint) and cause conflict with olds.

Upvotes: 0

Related Questions