如何根据自动布局调整子视图子视图的大小?
问题描述:
我有一个NSView让我打电话详细视图在我的主视图控制器中,所有的自动布局约束将被添加到与主视图相关。我将添加一个子视图让这个子细节到这个细节视图基于用户输入。根据子细节视图,此子细节视图包含大量视图,其中添加了约束。在添加子细节到细节视图作为子视图我通过获取细节视图的框架并设置x = 0和y = 0;来设置框架。我的问题是,当用户最大化窗口,用户选择和我加入子细节以详细查看子详细的尺寸子视图保持相同,但子详细观点得到自动调整为每需要。任何人都可以指导我做错了什么。下面我分享你的代码,其中我在链接中添加子视图和输出视图 我不想要空白的蓝色空间。如何根据自动布局调整子视图子视图的大小?
NSRect f = detailView.frame;
f.origin.x = 0;
f.origin.y = 0;
ConfigLogin *subDetail = [[ConfigLogin alloc] initWithFrame:f];
[subDetail setWantsLayer:YES];
[subDetail setAutoresizingMask:NSViewWidthSizable|NSViewHeightSizable];
[subDetail setTranslatesAutoresizingMaskIntoConstraints:YES];
subDetail.layer.backgroundColor = [NSColor blueColor].CGColor;
subDetail.frame = f;
[detailView addSubview:detailView];
答
我能找到的同时加入了子视图,我们不加约束,以使视图适合超级查看答案。
+(void) fitSubViewToSuperView:(NSView *) subview superView:(NSView *) superView
{
NSLayoutConstraint *width = [NSLayoutConstraint
constraintWithItem:subview
attribute:NSLayoutAttributeWidth
relatedBy:0
toItem:superView
attribute:NSLayoutAttributeWidth
multiplier:1.0
constant:0];
NSLayoutConstraint *height = [NSLayoutConstraint
constraintWithItem:subview
attribute:NSLayoutAttributeHeight
relatedBy:0
toItem:superView
attribute:NSLayoutAttributeHeight
multiplier:1.0
constant:0];
NSLayoutConstraint *top = [NSLayoutConstraint
constraintWithItem:subview
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:superView
attribute:NSLayoutAttributeTop
multiplier:1.0f
constant:0.f];
NSLayoutConstraint *leading = [NSLayoutConstraint
constraintWithItem:subview
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:superView
attribute:NSLayoutAttributeLeading
multiplier:1.0f
constant:0.f];
[superView addConstraint:width];
[superView addConstraint:height];
[superView addConstraint:top];
[superView addConstraint:leading];
}