我未能将我的应用程序从 Autoresize 迁移到 Autolayout 机制。我所需要的只是一个具有动态大小的视图和子视图,它们将连接到与它们的父视图相同大小的左上角。在 IB 中,我将 PieView(我的超级视图)的大小设置为 186x186。并让 IB 生成所有需要的约束(我将在代码中创建新的约束):
PieView.m -updateConstraints()
- (void)updateConstraints {
[super updateConstraints];
[self removeConstraintsAffectingViewAndSubviews];
[self setTranslatesAutoresizingMaskIntoConstraints:NO];
CGFloat sizeCoef = 0.7f;
CGFloat percent = [self.category getFillinPercent] / 100.0f;
percent = percent > 1.0f ? 1.0f : percent;
sizeCoef += (1.0f - sizeCoef) * percent;
NSLayoutConstraint *width = [NSLayoutConstraint constraintWithItem:self
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0f
constant:100.f];//kDiameter * sizeCoef];
NSLayoutConstraint *height = [NSLayoutConstraint constraintWithItem:self
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0f
constant:100.0f];//kDiameter * sizeCoef];
//_imgEmptyCircle, _imgFullCircle - UIImageViews
NSDictionary *views = NSDictionaryOfVariableBindings(_imgEmptyCircle, _imgFullCircle, self);
NSDictionary *metrics = @{@"height":@100.0};
[self addConstraints:@[width, height]];
NSString *visualForm = @"H:|[_imgEmptyCircle(height)][_imgFullCircle(height)]|";
NSArray *horizontalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:visualForm
options:0
metrics:metrics
views:views];
visualForm = @"V:|[_imgEmptyCircle(height)][_imgFullCircle(height)]|";
NSArray *verticalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:visualForm
options:0
metrics:metrics
views:views];
[self addConstraints:verticalConstraints];
[self addConstraints:horizontalConstraints];
}
结果真的让我吃惊。蓝色的如我所愿正确显示,但绿色的有奇怪的行为。
当然我有错误:无法同时满足约束。
第一个imageView :
NSIBPrototypingLayoutConstraint:0xa2795d0 'IB 在构建时自动生成用于固定框架的视图' V:[UIImageView:0x8a37150(186)]>
NSLayoutConstraint:0xa0305c0 V:[UIImageView:0x8a37150(100)]
第二个imageView :可能
是同一个
对于 PieView:
( NSLayoutConstraint:0x8a40750 V:[CEPieView:0x8a36e50(100)], NSLayoutConstraint:0xa030570 V:|-(0)-[UIImageView:0x8a37150] (名称: '|':CEPieView:0x8a36e50), NSLayoutConstraint:0xa0305c0 V:[UIImageView :0x8a37150(100)], NSLayoutConstraint:0xa0305f0 V:[UIImageView:0x8a37150]-(0)-[UIImageView:0xa277cf0]> NSLayoutConstraint:0xa030620 V:[UIImageView:0xa277cf0(100)], NSLayoutConstraint:0xa030650 V:[UIImageView: 0xa277cf0]-(0)-|(名称:'|':CEPieView:0x8a36e50))
请给我一个建议如何解决它。如何借助 AutoLayout 机制创建和旧的自动调整掩码(UIViewAutoresizingFlexibleHeight、UIViewAutoresizingFlexibleWidth)。任何帮助将不胜感激。