问题
I have a free version of my app and I remove + add autolayout constraints (to hide a premium feature), however if the user purchases my app I'd like to revert back to to the constraints set by interface builder.
I'm hoping there's a method which will achieve this, but I haven't been able to find it so far?
Here's what I have
if (!purchased) {
[self.tblOtherAccounts addConstraints:[NSLayoutConstraint
constraintsWithVisualFormat:@"V:[tblOtherAccounts(==0)]"
options:0
metrics:nil
views:NSDictionaryOfVariableBindings(tblOtherAccounts)]];
NSDictionary *views = @{ @"tblOtherAccounts" : self.tblOtherAccounts,
@"butBackAllAc" : butBackAllAc };
[self.view removeConstraints:[NSLayoutConstraint
constraintsWithVisualFormat:@"V:[tblOtherAccounts]-(12)-[butBackAllAc]"
options:0
metrics:nil
views:views]];
[self.view addConstraints:[NSLayoutConstraint
constraintsWithVisualFormat:@"V:[tblOtherAccounts]-(0)-[butBackAllAc]"
options:0
metrics:nil
views:views]];
}
回答1:
Add an IBOutlet to store your constraint in your ViewController :
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *myConstraint;
Then update its value :
_myConstraint.constant = 100.0f;
[_myView setNeedsUpdateConstraints];
[_myView layoutIfNeeded];
Regarding your comment on setting the relation to "equals", I don't think you'll be able to do that.
One thing you can do though is use your storyboard-generated constraint as a placeholder :
NSLayoutConstraint *newConstraint = [NSLayoutConstraint constraintWithItem:_myConstraint.firstItem
attribute:_myConstraint.firstAttribute
relatedBy:_myConstraint.relation
toItem:_myConstraint.secondItem
attribute:_myConstraint.secondAttribute
multiplier:_myConstraint.multiplier
constant:_myConstraint.constant];
[_myConstraint.secondItem removeConstraint:_myConstraint];
[constraint.secondItem addConstraint:newConstraint];
Of course the code above will create an exact duplicate of your constraint, but you can edit it to change the appropriate values to fit your needs.
回答2:
I think, you cannot do exactly that. You need to perform that logic in code. I.e. apply some constraints, then, on user action, apply another set of constraints.
Example: You have 2 constraints:
@property ... topConstraint;
@property ... leadingConstraint;
At the start you assign them some values:
topConstraint.constant = 100;
leadingConstraint.constant = 100;
After some user action, modify them:
topConstraint.constant = 150;
leadingConstraint.constant = 150;
来源:https://stackoverflow.com/questions/30433439/objc-revert-to-interface-builder-autolayout-constraints-after-adding-removin