简体   繁体   English

使用自动布局以编程方式创建视图层次结构

[英]Create view hierarchy programmatically with Auto Layout

I want to create a view hierarchy programmatically using Auto Layout The hierarchy has the following structure: UIView -> UIWebView I want to leave some space for a UIToolbar at the bottom of the UIView. 我想使用“自动布局”以编程方式创建视图层次结构。层次结构具有以下结构:UIView-> UIWebView我想在UIView底部为UIToolbar留一些空间。

The result should be as in this xib file: 结果应与以下xib文件相同: 在此处输入图片说明

Code so far: 到目前为止的代码:

- (void)loadView
{
    UIView *view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];    
    self.view = view;

    self.webView = [[UIWebView alloc] init];
    self.webView.scalesPageToFit = YES;
    [self.view addSubview:self.webView];

    self.view.translatesAutoresizingMaskIntoConstraints = NO;    
    self.webView.translatesAutoresizingMaskIntoConstraints = NO;

    NSDictionary *nameMap = @{@"webView" : self.webView};

    NSArray *c1Array =
    [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[webView]-0-|"
                                            options:0
                                            metrics:nil
                                              views:nameMap];

    NSArray *c2Array =
    [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[webView]-45-|"
                                            options:0
                                            metrics:nil
                                              views:nameMap];

    [self.view addConstraints:c1Array];
    [self.view addConstraints:c2Array];
}

When I trace using: 当我使用跟踪时:

po [[UIWindow keyWindow] _autolayoutTrace]

I get that both UIView and UIWebView have ambiguous layout. 我知道UIView和UIWebView的布局都不明确。

What could be the problem with my approach? 我的方法可能有什么问题?

You shouldn't set translatesAutoresizingMaskIntoConstraints to NO for the controller's self.view. 您不应将控制器的self.view的translationsAutoresizingMaskIntoConstraints设置为NO。 If you remove that line, the constraints you have should be adequate. 如果删除该行,则约束应足够。 BTW, there's no need for the zeros in your format string (although they don't hurt either), 顺便说一句,您不需要在格式字符串中使用零(尽管它们也不会损坏),

this "H:|[webView]|" 这个"H:|[webView]|" is equivalent to this "H:|-0-[webView]-0-|" 等效于此"H:|-0-[webView]-0-|" .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM