iOS8 Auto layout programatically pin to relative layout margin

荒凉一梦 提交于 2019-11-30 18:29:37

In iOS8, the visual format language has been updated so that "|-" or "-|" will default to using a spacing defined by the superview's layoutMargins property.

So the answer using visual format language is as follows:

// programmatically set the layoutMargins, only if
// you want non-default values and they are not already set in IB!
self.contentView.layoutMargins = UIEdgeInsetsMake(0,42,0,42); // set left and right margins to 42

// assume: seperatorView is already a subview of self.contentView

// separatorView will use the constraints because we write "-" between it and the superview edge
NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"|-[separatorView]-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(separatorView)];
[self.contentView addConstraints:constraints];

If you want to refer to the layout margins when creating the constraints via the direct API, then you use the new iOS8 only layout attributes:

NSMutableArray * constraints = [NSMutableArray array]; 
[constraints addObject:[NSLayoutConstraint constraintWithItem:self.contentView 
     attribute:NSLayoutAttributeLeftMargin 
     relatedBy:NSLayoutRelationEqual 
     toItem:separatorView
     attribute:NSLayoutAttributeLeft
     multiplier:1.0
     constant:0]];
[constraints addObject:[NSLayoutConstraint constraintWithItem:self.contentView 
     attribute:NSLayoutAttributeRightMargin 
     relatedBy:NSLayoutRelationEqual 
     toItem:separatorView
     attribute:NSLayoutAttributeRight
     multiplier:1.0
     constant:0]];
[self.contentView addConstraints:constraints];

I agree, "In iOS8, the visual format language has been updated so that "|-" or "-|" will default to using a spacing defined by the superview's layoutMargins property."

So, You should tick the option “Constrains to margin” when you use Interface builder to assist your layout. If so, then it does work.

If problem was still not solved, could you give me a demo project?

Added: This article whcih show us the function of new ios8 API preservesSuperviewLayoutMargins, wish it be more helpful.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!