2014-02-26 49 views
5

我有麻烦让我的子视图正确调整使用Autolayout。为了说明我的观点,我整理了一个简约的例子。Cocoa Autolayout和子视图调整大小

首先,我创建了一个新的NSViewController并添加了一个子视图(在这个特殊情况下是一个NSTextView)并添加了Autolayout约束。

enter image description here

我加入自定义视图我MainMenu.xib并设置自动布局约束太多。

enter image description here

最后,我创建了视图控制器的实例,并把它认为我的自定义视图中。

#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 

由于“Autoresizes子视图”在这两个XIB文件被选中,我预计NSTextView当我调整主窗口调整大小。但是,它只是停留在原地。

enter image description here

缺少什么我在这里?这让我困惑了几天。

感谢, 迈克尔·克努森

回答

3

你NSTextView包含视图不必其父任何约束,在这种情况下,你的窗口。您添加的视图没有调整大小,因为您的视图并未通过其父项的约束“连接”。如果您想以编程方式执行此操作,您可能需要调查addConstraint:方法。

请参阅Apple's docs了解更多信息。

+0

如果你看看我的文章的第一张截图,看来该NSTextView(或者更准确地说是在NSScrollView其所嵌入)是我的视图控制器的IBOutlet中视图的子视图。自动布局约束与该观点有关,对吧? –

+0

我其实是通过编程来做实验,但不知何故,最终导致我无法调整任何东西。在编程添加视图后,很难简单地“抓住”窗口边角。猜猜现在是时候回到文档并再次尝试。 –

+0

是的,自动布局约束是关于文本视图的*视图*(即父视图)的。 – SevenBits

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]; 
} 
+1

辉煌。这应该是被接受的答案。 – RajV

相关问题