Cocoa自动布局和子视图的大小调整

5
我在使用Autolayout时遇到了子视图无法正确调整大小的问题。为了说明我的观点,我制作了一个简单的示例。
首先,我创建了一个新的NSViewController,并添加了一个子视图(在这种情况下是NSTextView),并添加了Autolayout约束。
然后,我向MainMenu.xib添加了一个自定义视图,并为其设置了Autolayout约束。
最后,我创建了一个视图控制器的实例,并将其视图放入自定义视图中。
#import "AppDelegate.h"
#import "MyViewController.h"

@interface AppDelegate()
@property (weak) IBOutlet NSView *customView;
@end

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    MyViewController *myViewController = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil];

    [self.customView addSubview:myViewController.view];
    myViewController.view.frame = self.customView.bounds;
}

@end

由于两个xib文件中都选中了“自动调整子视图”的选项,因此我希望当我调整主窗口大小时,NSTextView也会随之调整大小。但事实并非如此,它只是停留在原地。

enter image description here

我错过了什么?这已经让我困惑了几天。

谢谢, Michael Knudsen

2个回答

8

以防其他人遇到同样的问题。我最终通过以下方式解决了它(感谢@SevenBits指引我方向)。

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    MyViewController *myViewController = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil];

    [self.customView addSubview:myViewController.view];

    myViewController.view.translatesAutoresizingMaskIntoConstraints = NO;

    NSArray *verticalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[subView]|"
                                                                           options:0
                                                                           metrics:nil
                                                                             views:@{@"subView" : myViewController.view}];

    NSArray *horizontalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[subView]|"
                                                                           options:0
                                                                           metrics:nil
                                                                             views:@{@"subView" : myViewController.view}];

    [self.customView addConstraints:verticalConstraints];
    [self.customView addConstraints:horizontalConstraints];
}

3

您的NSTextView的包含视图没有任何约束到其父视图的限制,即您的窗口。您添加的视图未被调整大小,因为由于您的视图未通过约束与其父视图“连接”起来。如果您想以编程方式执行此操作,则可能需要使用addConstraint:方法进行研究。

有关更多信息,请参见Apple的文档


如果您查看我帖子中的第一张截图,似乎NSTextView(或更准确地说是它嵌入其中的NSScrollView)是我的视图控制器的IBOutlet视图的一个子视图。自动布局约束是针对该视图的,对吗? - Michael Knudsen
我实际上已经尝试过以编程方式来做这件事,但不知怎么的,最终导致我完全无法调整大小。在以编程方式添加视图后,根本无法“抓住”窗口的角落/侧面。看来是时候返回文档,再次尝试了。 - Michael Knudsen
是的,自动布局约束是相对于容纳文本视图的视图(即父视图)而言的。 - SevenBits
嗯,那么当你说文本视图没有与其父视图“连接”时,你的意思是什么? - Michael Knudsen
谢谢。现在更有意义了。我会尝试进行实验。敬请关注 :-) - Michael Knudsen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接