视觉格式NSLayoutConstraints中心视图 [英] Centering view with visual format NSLayoutConstraints
问题描述
我想用视觉语言格式居中视图。
I am trying to center a view using the visual format language.
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_progressView(300)]-|" options:NSLayoutFormatAlignAllCenterY metrics:0 views:views]];
(的意见
是 NSDictionaryOfVariableBindings
包含 _progressView
)
它不集中我的观点(宽度:300)的 self.view
(:768宽)之内。它对齐它留下一个8像素的保证金,就好像我本来只写了 @H:| - [_ progressView(300)。
It does not center my view (width: 300) within the self.view
(width: 768). It aligns it left with an 8 pixel margin, as if I would have only written @"H:|-[_progressView(300)"
.
时居中使用类似观点的唯一办法:?
Is the only way to center the view using something like:?
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:_progressView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual
toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]];
感谢
推荐答案
此格式字符串
@"H:|-[_progressView(300)]-|"
没有告诉自动版式为中心 progressView
。相反,它说, progressView
应该是300宽,对两边定义的标准保证金为上海华的边缘系统。显然,这不能被满足,所以自动布局滴一些约束(你可能会得到在控制台上的一些日志)。即你的情况下降的约束可能是在右边的空白。
doesn't tell AutoLayout to center progressView
. Instead it says that progressView
should be 300 wide and have a system defined standard margin on either side to the superview's edges. Obviously this can't be satisfied, so Auto Layout drops some of the constraints (you probably get some logs on the console). The constraint that is dropped in your case is probably the margin on the right.
要真正居中鉴于这是你必须使用冗长的约束方法,而不是视觉的字符串格式的SuperView,因为你已经想通了。但是,您可以轻松将它放入一个不错的类别是这样的:
To really center a view in it's superview you have to use the verbose constraint method instead of the visual string format, as you already figured out. However, you can easily put that into a nice category like this:
@interface UIView (MyLayout)
- (void)centerHorizontallyInSuperview;
@end
@implementation UIView (MyLayout)
- (void)centerHorizontallyInSuperview {
NSLayoutConstraint *c;
c = [NSLayoutConstraint constraintWithItem:self
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.superview
attribute:NSLayoutAttributeCenterX
multiplier:1
constant:0];
[self.superview addConstraint:c];
}
@end
这篇关于视觉格式NSLayoutConstraints中心视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!