我有一个XIB视图。
当我将它添加到我的视图中时,我希望宽度和高度适合iOS设备。
然而,它并不合适。
如果我使用自动布局,它将适合屏幕。但我该如何使用呢?
在下面的代码示例中,它采用XIB文件的Bounds
。因此它不适合视图。我该如何解决这个问题?
-(id)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
self.myView=[[[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil] lastObject];
self.bounds=self.myView.bounds;
[self addSubview:self.myView];
}
return self;
}
答案 0 :(得分:0)
加载您的视图,然后
[_subview setTranslatesAutoresizingMaskIntoConstraints:NO];
[_contentView addSubview:_subview];
[self activateConstraintsForView:_subview respectToParentView:_contentView];
使用此功能:
- (void)activateConstraintsForView:(UIView *)view respectToParentView:(UIView *)parentView
{
NSLayoutConstraint *bottomConstraint = [NSLayoutConstraint constraintWithItem:view
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:parentView
attribute:NSLayoutAttributeBottom
multiplier:1.0
constant:0];
NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem:view
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:parentView
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:0];
NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:view
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:parentView
attribute:NSLayoutAttributeLeft
multiplier:1.0
constant:0];
NSLayoutConstraint *rightConstraint = [NSLayoutConstraint constraintWithItem:view
attribute:NSLayoutAttributeRight
relatedBy:NSLayoutRelationEqual
toItem:parentView
attribute:NSLayoutAttributeRight
multiplier:1.0
constant:0];
[NSLayoutConstraint activateConstraints:[NSArray arrayWithObjects:topConstraint, leftConstraint, bottomConstraint, rightConstraint, nil]] ;
}
希望,这有帮助。
答案 1 :(得分:0)
在你的initWithFrame方法中,最后添加:
[self setConstraintsOfView:self.myView withRespectToParentView:self];
在课程结束时添加以下方法:
-(void)setConstraintsOfView:(UIView *)subView withRespectToParentView:(UIView *)parentView
{
NSDictionary *viewsDictionary = @{@"subView":subView};
NSDictionary *metrics =@{@"offset":@0};
NSArray *heightConstraint = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-offset-[subView]-offset-|"
options:0
metrics:metrics
views:viewsDictionary];
NSArray *widthConstraint = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-offset-[subView]-offset-|"
options:0
metrics:metrics
views:viewsDictionary];
[parentView addConstraints:heightConstraint];
[parentView addConstraints:widthConstraint];
}
VFL比设置每个约束容易得多。此方法相对于superview设置子视图的top,bottom,leading和trailing space = 0。
我认为你想实现这个目标: https://github.com/PrajeetShrestha/ConstraintTest