我试图尽可能接近苹果的实现,承认存在NSLayoutConstraint
,所以我简单地定义了一组简洁的自动布局宏,它们从属性和关系中删除前缀,并将约束创建包装在一个构造函数类似的宏中(也省略了我从不使用的乘数参数):
Constraint
ConstantConstraint
VisualConstraints
VisualConstraintWithMetrics
为了将多个简单的约束附加到视图中,我将它们包装在数组文字中。我总是在非零常量前面加上一个符号,以强调位移。在实践中它看起来像这样(实例变量指的是视图):
[self.view addConstraints:
@[Constraint(_verticalSeparator, CenterX, Equal, _top, CenterX, 0),
Constraint(_verticalSeparator, CenterY, Equal, _top, CenterY, +22),
Constraint(_verticalSeparator, Height, Equal, _localWeather, Height, 0),
Constraint(_localWeather, CenterY, Equal, _verticalSeparator, CenterY, 0),
Constraint(_addLocation, CenterY, Equal, _verticalSeparator, CenterY, 0),
Constraint(_touchDown, Trailing, Equal, _verticalSeparator, Trailing, -1),
Constraint(_touchDown, CenterY, Equal, _localWeather, CenterY, 0),
Constraint(_touchDown, Width, Equal, _localWeather, Width, +26),
Constraint(_touchDown, Height, Equal, _localWeather, Height, 0)
]];
id f = @"[_localWeather]-space-[_verticalSeparator]-space-[_addLocation]";
[self.view addConstraints:
VisualConstraintWithMetrics(f, @{@"space": @11},
_localWeather, _verticalSeparator, _addLocation)];
[_tableCell addConstraint:ConstantConstraint(_tableCell, Height, Equal, 44)];
在处理所有共享相同设置的视图组时,我会像这样枚举数组文字:
[@[_top, _middle, _bottom, _touchDown, _verticalSeparator]
enumerateObjectsUsingBlock:^(UIView *view, NSUInteger idx, BOOL *stop) {
view.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:view];
}];
水平填充superview
经常发生,以至于它提升到自己的宏中:
[@[_top, _middle, _bottom] enumerateObjectsUsingBlock:horizontallyFillSuperview];
随着我风格的发展,我会更新这个答案……</p>